gpt4 book ai didi

javascript - 如何获取具有特定数据属性的 html 节点?

转载 作者:行者123 更新时间:2023-11-28 18:56:31 24 4
gpt4 key购买 nike

在javaScript中,获取特定html节点的最佳方法是什么,我知道属性名称和属性值,并且许多html节点可以具有相同的属性名称?属性名称是数据属性。

这是一些示例 html:

<div class="misc1" data-test="value1" data-test="value2"></div>
<div class="misc2" data-test="value3" data-test="value4"></div>

如果我想使用 data-test="value3" 获取 html 节点,我是否需要执行以下操作:

  var elements = document.querySelectorAll("[data-test]");
for (i = 0; i < elements.length; i++) {
for(x = 0; x < elements[i].attributes.length; x++) {
//Do an attribute value check??
}
}

我不想使用 jQuery,但我可以在代码方面获得一些帮助吗?

最佳答案

您的attribute selector可以变得更具体,如下所示:

var elements = document.querySelectorAll('[data-test="value3"]');

属性选择器还有多种其他变体:

  • [attr] Represents an element with an attribute name of attr.
  • [attr=value] Represents an element with an attribute name of attr and whose value is exactly "value".
  • [attr~=value] Represents an element with an attribute name of attr whose value is a whitespace-separated list of words, one of which is exactly "value".
  • [attr|=value] Represents an element with an attribute name of attr. Its value can be exactly “value” or can begin with “value” immediately followed by “-” (U+002D). It can be used for language subcode matches.
  • [attr^=value] Represents an element with an attribute name of attr and whose value is prefixed by "value".
  • [attr$=value] Represents an element with an attribute name of attr and whose value is suffixed by "value".
  • [attr*=value] Represents an element with an attribute name of attr and whose value contains at least one occurrence of string "value" as substring.
  • [attr operator value i] Adding an i before the closing bracket causes the value to be compared case-insensitively (for characters within the ASCII range).

关于javascript - 如何获取具有特定数据属性的 html 节点?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33535611/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com