getElementById like something

Hello. Is there a way for getElementById to perform a function if it finds an ID that is like something - sort of like a wildcard? I want the function to run if the ID contains “_price”. It will have something like 247_price or 23_price. I want to ignore the first number and only concern myself with whether or not it has “_price” in it. Thanks!

if (document.getElementById("LIKE_price")) {

   //do this

} else {

   //do this


No, but if you can get yourself a reference to all the possible elements, you can iterate through them and use string functions to inspect the value of the id attribute. This is perfectly functional, but the efficiency is poor.

var elems = document.getElementsByTagName("*");
var matches = [];
for (var i=0, m=elems.length; i<m; i++) {
    if (elems[i].id && elems[i].id.indexOf("_price") != -1) {

If possible, specify a tag name, like div instead of *. And/or specify a more restrictive container element. For example, use myNavContainer.getElementsByTagName…

that totally works. thanks crmalibu!

Of course ids can’t start with a number and so you presumably were only using the ids you mentioned as invalid examples.

Funny thing felgall, on this script that I am working on (I didn’t write it) they do start with numbers like 115_price, etc. But it works. Hmmmm…

<div id="115_total" style="height: 10px; font-size: 15px;">700</div></td>

It will still work, but it violates the HTML spec. It’s best practice to NOT start your ids with numbers.

I’ll change it. Thanks for the heads up.

If it’s possible for you to change it, how about setting the same className to all elements that should be affected? That way you could use getElementsByClassName to fetch them all. You could also store the actual price in the class, but as with ID it mustn’t start with a number so you’d have to prefix it with a letter.

The benefit is not having to loop every element in the DOM (*).

I had already suggested this to change in a previous post as well.

Starting ids with numbers can cause a problem in some cases with different browsers as well which I had faced before.

As per powerbuoy’s suggestion on using class names:

There are some different examples of implementing a document.getElementsByClassName function as it’s not implemented in all browsers.

It’s always best to check if there is a native version available (Firefox 3 etc), something like…

// If the native function isn't available, use a custom one.
if(typeof document.getElementsByClassName !== 'function'){
    document.getElementsByClassName = function(.....