Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

document.getElementById + regex

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

like image 283
user502014 Avatar asked May 19 '11 16:05

user502014


People also ask

What is document getElementById () value?

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.

Is JavaScript regex fast?

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.

What does the document getElementById () method return?

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.

Can you use a variable in getElementById?

Yes, Mate, you can. You can use a variable as the argument for any function.


1 Answers

Yep. document.querySelectorAll seems to be good here.

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

Borrowed from StackOverFlow

MDN Link here.

like image 110
paje007 Avatar answered Sep 19 '22 10:09

paje007