How To Get All Elements Whose ID Starts With Specific String In JS

Get all elements whose ID starts with specific String in JS

In this article, you’ll learn how to get all elements whose ID starts with specific string in JS by using JQuery’s selector or using the document.querySelectorAll() function. Let’s go into detail now.

Get all elements whose ID starts with specific string in JS

For the sake of simplicity, we’ll be using the example of changing the color of any <input> Elements to red if they have their ID starts with "form-", seen here:

Code:

<form>
    <div>
        Username: <input name="username" type="text" id="form-username">
    </div>
    <div>
        Password: <input name="password" type="password" id="form-password">
    </div>
    <div>
        Phonenumber: <input name="phonenumber" type="text" id="non-imp-phonenumber">
    </div>
    <div>
        Email: <input name="email" type="email" id="non-imp-email">
    </div>
</form>

Using the JQuery Selector

Note that: If you are dealing with HTML Elements in JavaScript, use JQuery.

JQuery is a JavaScript library specialized in the traversal and manipulation of HTML DOM Elements for animations, and event handling, in addition to being able to use Ajax. You can download it here.

The fundamental method used in every JQuery selection is the JQuery Selector ("$()") which takes in a CSS selector, which, importantly, is able to detect DOM Elements by whether its ID starts with a specific string.

When using a CSS Selector to locate Elements with an ID that starts with a specific string, the general format looks like this:

`[id^="id_value"]`

Taking in all this, the code looks something like this:

Code:

function setFormIdToRed() {
	// Get all the Elements with an ID that starts with "form-"
	const elements = $(`[id^="form-"]`);

	// Set their background to red
	elements.css("background-color", "red");
}

setFormIdToRed();

Output:

Note that it is generally preferred in this situation to use a Template String (``), as the value of the ID must be encapsulated in double quotes ("") and needs something else to encapsulate the entire CSS Selector. While it is still possible to encapsulate the CSS Selector in single brackets (''), the utility of a Template String outweighs it.

The Template String is mostly used, in addition to working as a regular string, for its string interpolation (i.e., putting "${[code]}" inside the string). With this, we are able to get DOM Elements with IDs that start with a specific string in a readable way. For example:

function setIdStartToRed(idStart) {
	// Get all the Elements with an ID that starts with idStart
	const elements = $(`[id^="${idStart}"]`);

	// Set their background to red
	elements.css("background-color", "red");
}

setIdStartToRed("non-imp-");

Output:

Using the document.querySelectorAll() function (JavaScript)

If you don’t want to use JQuery, the Document class’ .querySelectorAll() function (or how you’d generally write it in most situations: document.getSelectorAll()) would be the replacement.

Similarly, the document.getSelectorAll() function also uses a CSS Selector to locate Elements. However, the function only returns a list of those Elements. As a result, by not using JQuery, which lets you interact with all of the Elements in that list without a loop, you will have to iterate over each Element separately to access them. For example:

function setFormIdToRed() {
	// Get all the Elements with an ID that starts with "form-"
	const elements = document.querySelectorAll(`[id^="form-"]`);

	// Set their background to red
	for (const element of elements) {
		element.style.backgroundColor = "red";
	}
}

setFormIdToRed();

Output:

Similarly to the JQuery method, you can also check for specific ID start.

Code:

function setIdStartToRed(idStart) {
	// Get all the Elements with an ID that starts with idStart
	const elements = document.querySelectorAll(`[id^="${idStart}"]`);

	// Set their background to red
	for (const element of elements) {
		element.style.backgroundColor = "red";
	}
}

setIdStartToRed("non-imp-");

Output:

Summary

To get all elements whose ID starts with specific string in JS, you can use JQuery’s selector with a CSS Selector that selects IDs that start with something ("[id^=...]") or use the document.querySelectorAll() function.

Maybe you are interested:

Leave a Reply

Your email address will not be published. Required fields are marked *