我目前正在尝试找出一种方法来获取元素的 ID,具体取决于它的类是否包含某些内容。我不确定是否有比我现在更好的方法来做到这一点,但环顾四周没有什么能完全符合我的需要。我目前拥有的代码是,我正在寻找一个 div 元素,其类包含字符串“one”,但不限于此。目前只有一个元素包含此字符串,但警报为我提供了 [Object NodeList](我可能把它过于复杂化了):
$idToMove = document.querySelectorAll('div[class^="one"]');
alert($idToMove);
最佳答案
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~=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 and whose first value is prefixed by "value".
关于javascript - 获取类包含给定字符串的元素的 ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37191206/