document.getElementById +正则表达式
document.getElementById
可以与正则表达式一起使用吗?
例如,一个页面上的 ID 将为 Product-1,而在另一页面上则为 product-3。 (不要问我为什么,但它显然无法更改。)
我想做的是运行 getElementById
查找 Product-x 的 Id,其中 x 是 1 或 3。
目前我有这样的东西:
var _container = document.getElementById("product-1") || document.getElementById("product-3");
它有效 - 但我想知道是否有更好的方法来做到这一点?
提前致谢
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
![扫码二维码加入Web技术交流群](/public/img/jiaqun_03.jpg)
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
是的。 document.querySelectorAll 在这里似乎很好。
借自 StackOverFlow
MDN 链接 此处。
Yep. document.querySelectorAll seems to be good here.
Borrowed from StackOverFlow
MDN Link here.
jQuery 选择器对此来说非常棒。
一个很好的例子是“开头”选择器,如下所示
$("*[id^=产品]")
jQuery selectors are awesome for this.
An great example would be the "starts with" selector like so
$("*[id^=product]")
所以你不能改变元素的id,但你可以添加一个类吗?
如果您将类产品添加到您的所有产品中,您就可以获得它们
全部通过
并拿走第一个
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
and take the first one