17

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

Gumbo
  • 643,351
  • 109
  • 780
  • 844
user502014
  • 2,241
  • 5
  • 24
  • 32
  • 1
    [jQuery selectors](http://api.jquery.com/category/selectors/) are _awesome_ for this. – pixelbobby May 19 '11 at 16:27
  • 2
    Strip the jQuery from the jQuery and get Sizzle, jQuery's selector engine: http://sizzlejs.com/ – Blender May 19 '11 at 16:28
  • +1 but if you're going to be doing _cool stuff_ like this, jQuery might help in other areas as well. Multi-purpose FTW. Ockham's Razor @Blender. – pixelbobby May 19 '11 at 16:30
  • Possible duplicate of [Javascript getElementById base on partial string](https://stackoverflow.com/questions/6991494/javascript-getelementbyid-base-on-partial-string) – Claire May 19 '18 at 09:04

3 Answers3

23

Yep. document.querySelectorAll seems to be good here.

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

Borrowed from StackOverFlow

MDN Link here.

Community
  • 1
  • 1
paje007
  • 1,001
  • 7
  • 9
10

jQuery selectors are awesome for this.

An great example would be the "starts with" selector like so $("*[id^=product]")

pixelbobby
  • 4,368
  • 5
  • 29
  • 49
0

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

megakorre
  • 2,213
  • 16
  • 23
  • 1
    Although this is nice & clean it is incompatible with IE 5.5, 6, 7 & 8. (http://www.quirksmode.org/dom/w3c_core.html#t11). Instead I would recommend trying this => http://pastie.org/2574711 – yekta Sep 22 '11 at 16:44