Borislav Hadzhiev
Last updated: Jan 3, 2022
Check out my new book
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.
<!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.
// ✅ 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]
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.
$
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.
// ✅ 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
.
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.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.