如何迭代包含所提供的属性之一的 HTML DOM 节点?
我希望能够为以下 CSS 选择器获取第一个匹配元素,然后是第二个,依此类推:
[att]
以下选择器不是有效的 CSS3 选择器,但这就是我想要实现的目标:
[att][0]
[att][1]
...
[att][n]
我可以组合多个就像上面的例子一样,选择器并迭代每个匹配的节点?
[att1],[att2]
如果使用本机 DOM 或 CSS3 选择器无法完成此操作,那么 XPath 查询也是一种选择。
I want to be able to get the first matching element, then the second, and so on, for the following CSS selector:
[att]
The below selectors are not valid CSS3 selectors, but that is what I'm trying to accomplish:
[att][0]
[att][1]
...
[att][n]
Can I combine multiple selectors and iterate over each matching node just like the example above?
[att1],[att2]
If this can't be done with native DOM or CSS3 selectors, then an XPath query is also an option.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果
document.querySelectorAll()
是一个选项,那么这将非常简单 - 只需传递选择器,浏览器将处理其余部分:只要浏览器支持它,它就可以与您传递的任何 CSS 选择器一起使用(在这种情况下,任何实现该功能的浏览器都应该已经这样做了)。因此,要选择具有
att1
、att2
或两者的元素,请按照注释中所述使用:If
document.querySelectorAll()
is an option, it will be very easy — just pass the selector and the browser will handle the rest:It works with any CSS selector you pass it provided the browser supports it (which in this case any browser implementing the function should already do). So to pick elements that have either
att1
,att2
or both, use this as mentioned in the comments:使用 jQuery:
此外,这也是可行的:
第一个将为您提供带有
att
属性的所有元素的列表。如果您不想使用 jQuery,您的代码将运行慢得多,因为执行此操作的逻辑方法是:jQuery 实际上更快的原因是因为它会使用可能的话使用XPath查询或其他方法,这将大大加快执行速度。当然,如果您愿意,您可以在上面的代码中实现 XPath。
Using jQuery:
Also, this works:
The first will give you a list of all elements with an
att
attribute. If you don't want to use jQuery, your code will run much slower since the logical way to do this is:The reason jQuery is actually faster is because it will use XPath queries or other methods when possible, which will greatly speed up the execution. Of course you could implement XPath in the above code if you want.