document.getElementById + regex

user502014 picture user502014 · May 19, 2011 · Viewed 14k times · Source

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

Answer

paje007 picture paje007 · Jun 16, 2016

Yep. document.querySelectorAll seems to be good here.

document.querySelectorAll('[id^=product]')

Borrowed from StackOverFlow

MDN Link here.