Get Element whose ID ends with specific String using JS

avatar

Borislav Hadzhiev

Last updated: Jan 3, 2022

banner

Check out my new book

Get Element whose ID ends with specific String using JS #

Use the document.querySelector() method to get an element whose id ends with a specific string, e.g. document.querySelector('[id$="example"]'). The method returns the first element that matches the selector. If no element matches the selector, null is returned.

Here is the HTML for the examples in this article.

index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <div id="abc_example">Box 1</div> <script src="index.js"></script> </body> </html>

And here is the related JavaScript code.

index.js
// ✅ get by ID Ending with `example` const element1 = document.querySelector('[id$="example"]'); console.log(element1); // 👉️ div#abc_example // ✅ get ALL elements whose ID ends with `example` const allElements = document.querySelectorAll('[id$="example"]'); console.log(allElements); // 👉️ [div#abc_example]
If you need to get all elements with an id attribute whose value ends with a specific string, use the querySelectorAll method instead.

We used the document.querySelector method to get the first element that has an id attribute, whose value ends with example.

If no matches are found, the method returns a null value.

You might be familiar with the dollar sign $ symbol, which has the same meaning when used with regular expressions.

Note that you could also prefix the selector with the specific type of element you want to match, to narrow down the results.

index.js
// ✅ get DIV by ID Ending with `example` const element1 = document.querySelector('div[id$="example"]'); console.log(element1); // 👉️ div#abc_example

The example above selects the first div element that has an id attribute, whose value ends with example.

If no element matches the provided selector, the querySelector method returns null. To make sure you dont try to access a property on a null value or try to invoke a method on one, you should handle this scenario.
index.js
const element1 = document.querySelector('div[id$="example"]'); if (element1) { // 👇️ "Box 1" console.log(element1.textContent); }

In the example, we checked if the element1 variable stores a truthy value before accessing the textContent property.

This helps us make sure we don't get an error by trying to access the property on a null value.

Use the search field on my Home Page to filter through my more than 3,000 articles.