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) {
matches.push(elems[i]);
}
}
If possible, specify a tag name, like div instead of *. And/or specify a more restrictive container element. For example, use myNavContainer.getElementsByTagName…
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 (*).
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(.....
}