Can document.getElementById
be used along with a regular expression?
For example an id on one page will be Product-1 while on another page it will be product-3. (Don't aks me why but it cannot be changed apparently.)
What I would like to do is run a getElementById
looking for an Id of Product-x where x is either 1 or 3.
Currently I have something like this:
var _container = document.getElementById("product-1") || document.getElementById("product-3");
which works - but I wonder if there is a better way of doing this?
Thanks in advance
The getElementById() method returns an element with a specified value. The getElementById() method returns null if the element does not exist. The getElementById() method is one of the most common methods in the HTML DOM. It is used almost every time you want to read or edit an HTML element.
Introduction to Regular ExpressionsA regular expression (also called regex for short) is a fast way to work with strings of text. By formulating a regular expression with a special syntax, you can: search for text in a string.
The Document method getElementById() returns an Element object representing the element whose id property matches the specified string. Since element IDs are required to be unique if specified, they're a useful way to get access to a specific element quickly.
Yes, Mate, you can. You can use a variable as the argument for any function.
Yep. document.querySelectorAll seems to be good here.
document.querySelectorAll('[id^=product]')
Borrowed from StackOverFlow
MDN Link here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With