javascript document.getElementById + 正则表达式

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6061760/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 19:19:50  来源:igfitidea点击:

document.getElementById + regex

javascriptgetelementbyid

提问by user502014

Can document.getElementByIdbe used along with a regular expression?

可以document.getElementById和正则表达式一起使用吗?

For example an id on one page will be Product-1while on another page it will be product-3. (Don't aks me why but it cannot be changed apparently.)

例如,一个页面上的 id 将是Product-1而在另一页面上它将是product-3。(不要问我为什么,但它显然不能改变。)

What I would like to do is run a getElementByIdlooking for an Id of Product-xwhere xis either 1 or 3.

我想做的是运行getElementById查找Product-x的 ID,其中x是 1 或 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

提前致谢

回答by pixelbobby

jQuery selectorsare awesomefor this.

jQuery 选择器在这方面非常棒

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

一个很好的例子是“开头的选择器,就像这样$("*[id^=product]")

回答by paje007

Yep. document.querySelectorAll seems to be good here.

是的。document.querySelectorAll 在这里似乎很好。

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

Borrowed from StackOverFlow

StackOverFlow借来的

MDN Link here.

MDN 链接在这里。

回答by megakorre

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

所以你不能改变元素的 id 但你可以添加一个类吗?如果您将类产品添加到所有产品中,则可以通过

document.getElementsByClassName("product")

and take the first one

并采取第一个