【问题标题】:Get the ID of an element where the class contains a given string获取类包含给定字符串的元素的 ID
【发布时间】:2016-09-08 12:59:18
【问题描述】:

我目前正在尝试找出一种方法来获取元素的 ID,具体取决于其类是否包含某些内容。我不确定是否有比我现在更好的方法来做到这一点,但是环顾四周,没有什么能完全满足我的需要。我目前拥有的代码是,我正在寻找一个 div 元素,其类包含字符串“one”但不限于此。目前只有一个元素包含此字符串,但警报为我提供了 [Object NodeList](我可能过于复杂了):

$idToMove = document.querySelectorAll('div[class^="one"]');
        alert($idToMove);

【问题讨论】:

标签: javascript html css


【解决方案1】:

document.querySelectorAll() 返回一个节点列表(有点像一个数组),如果你确定只有一个,你有几个选项。

1) 改用.querySelector

// returns the first node that matches
var elm = document.querySelector('div[class~="one"]');
console.log(elm.id);

2) 访问返回列表中的第一个元素:

// returns all nodes that match
var elms = document.querySelectorAll('div[class~="one"]');
console.log(elms[0].id);

确保.querySelector 的检查返回为空,.querySelectorAll 的长度检查返回。

还要注意,我使用的是~= 而不是^=。您可以阅读on the MDN 了解所有相等运算符之间的区别。但是对于这两个:

[属性~=值] 表示属性名称为 attr 的元素,其值是以空格分隔的单词列表,其中一个恰好是“值”。

[属性^=值] 表示属性名称为 attr 且第一个值以“value”为前缀的元素。

【讨论】:

  • 感谢您的回答!我似乎返回 null (我已使用部分分辨率 1 来解决此问题)。难道我正在设置类以在 php 中包含“one”吗?它成功地使该类包含字符串“one”但是当我尝试 console.log 它错误它不能给我 null 的 id。
  • 更新答案,您需要~= 而不是^=
  • 感谢您的帮助,这行得通!非常感谢!
【解决方案2】:

首先从 DOM 中获取元素,然后从该元素获取 id 属性:

1- 如果您只需要第一个元素,请像这样使用 querySelector:

let elms = document.querySelector('div[class~="one"]')[0].id
console.log(elms)

2- 如果您需要所有具有此类的元素,请像这样使用 querySelectorAll:

let elms = document.querySelectorAll('div[class~="one"]')

for(let i=0; i<elms.length; i++)
{
console.log(elms[i].id)
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-21
    • 1970-01-01
    • 2016-04-19
    • 2016-10-16
    • 2013-09-17
    • 1970-01-01
    相关资源
    最近更新 更多