问题
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
回答1:
jQuery selectors are awesome for this.
An great example would be the "starts with" selector like so $("*[id^=product]")
回答2:
Yep. document.querySelectorAll seems to be good here.
document.querySelectorAll('[id^=product]')
Borrowed from StackOverFlow
MDN Link here.
回答3:
so you cant change the id of the elements but can you add a class? if you add the class product to all your products you can get them all by
document.getElementsByClassName("product")
and take the first one
来源:https://stackoverflow.com/questions/6061760/document-getelementbyid-regex