document.getElementById + regex

怎甘沉沦 提交于 2019-12-07 11:38:49

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!