【发布时间】:2023-03-04 20:47:01
【问题描述】:
本着更加熟悉 DOM 和递归的精神,我决定从头开始重新创建 getElementsByClassName(仅限原版 JS,没有 jQuery)。目前,我可以在 DOM 中找到所有具有我想要的类的元素,但我无法想出一种方法来仅获取具有两个特定类(或更多)的元素。
<div class="one two">
<h1 class="one">
<span class="one two">
</h1>
</div>
我当前的实现返回了我期望的结果,每个包含“one”类的元素都会返回:
getElementsByClassName('one');
[<div class="one two"></div>, <h1 class="one"></h1>, <span class="one two"</span>]
我想要达到的目的:
getElementsByClassName('one two');
[<div class="one two"></div>, <span class="one two"</span>]
我遇到的问题之一是 classList.contains:
element.classList;
// ['one, 'two'];
element.classList.contain("one");
//returns true since the value actually exists
//PROBLEM:
element.classList.contains("one two");
//this is looking for "one two" in the array and not 'one' and 'two'.
//this returns false & my code breaks
//How would I be able to do something like this, even if it
//means recreating my own helper contains function?
contains('one','two');
我的功能:
var getElementsByClassName = function(className){
var results = [];
function getClass(nodeList){
var childList = nodeList.children;
_forEach(childList, function(node) {
//1st level body check
if(node.classList && node.classList.contains(className)){
results.push(node);
}
//has children, recurse
if(node.children) {
getClass(node);
}
else {
getClass(node);
}
});
}
getClass(document.body);
return results;
}
//Helper forEach function to iterate over array like DOM objects
var _forEach = function(collection, func) {
for(var i = 0; i < collection.length; i++) {
func(collection[i], i, collection);
}
}
【问题讨论】:
-
['one', 'two'].every(function(className) { return node.classList.contains(className); }) -
谢谢,我刚开始学习编程几个月和几周前的函数式编程。是时候剖析这个 =)。
-
您的道路上一切顺利,而且您拥有关键要素:真正努力学习。好东西。 (这就是我没有做实现的原因,只是指出你会如何。)
-
请注意它返回一个live list of nodes。您将不得不使用变异观察者来更新返回的列表。
标签: javascript dom contains