【问题标题】:Find all DOM elements which ID contains a string using vanilla Javascript [duplicate]使用vanilla Javascript查找ID包含字符串的所有DOM元素[重复]
【发布时间】:2018-12-19 18:43:19
【问题描述】:

查找 ID 包含字符串的所有 DOM 元素,但我想使用 vanillaJS。我知道在here 中有一个使用 jQuery 的解决方案,但在这种情况下,我只想使用纯 javascript。

我知道这个:

document.querySelectorAll("[id='parteOfanID']")

我们可以获取属性id为“parteOfanID”的所有元素。

谢谢

【问题讨论】:

  • 你的意思是包含相同的id名称?

标签: javascript


【解决方案1】:

您可以将*= 与属性选择器[] 一起使用,例如:

document.querySelectorAll('[id*="string_here"]')

console.log(document.querySelectorAll('[id*="identifier_"]').length);
<span id="test"></span>
<span id="identifier_1"></span>
<span id="identifier_2"></span>
<span id="identifier_3"></span>
<span id="test"></span>
<span id="identifier_4"></span>
<span id="test"></span>

【讨论】:

    【解决方案2】:

    使用 document.querySelectorAll() 获取 CSS 选择器(如 jQuery)并返回 NodeList

    var elements = document.querySelectorAll('[id*="some text"]');
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-05-08
      • 2018-03-17
      • 2016-03-03
      • 2020-04-26
      • 2022-12-15
      • 1970-01-01
      • 2010-11-17
      相关资源
      最近更新 更多