这是搜索特定div的所有祖先的代码。如何以我找到所有祖先的方式修改该代码,但只能使用特定的类(例如'myclass')?
let nodes = [];
let element = document.getElementById('find');
nodes.push(element);
while(element.parentElement) {
nodes.unshift(element.parentElement);
element = element.parentElement;
}
<div id="n1" class="something">
<div id="n2" class="myclass">
<div id="n3" class="something">
<div id="n4" class="myclass">
<button id="find"></button>
</div>
</div>
<div id="n5" class="something">
<div id="n6" class="myclass">
</div>
</div>
</div>
</div>
所以在这个例子中,它会找到id为n4和n2
的div答案 0 :(得分:1)
只需检查节点是否具有相应的类,并仅在
时按下它
let nodes = [];
let element = document.getElementById('find');
nodes.push(element);
while (element.parentElement) {
if (element.parentElement.classList.contains('myclass')) {
nodes.unshift(element.parentElement);
}
element = element.parentElement;
}
console.log(nodes);
<div id="n1" class="something">
<div id="n2" class="myclass">
<div id="n3" class="something">
<div id="n4" class="myclass">
<button id="find"></button>
</div>
</div>
<div id="n5" class="something">
<div id="n6" class="myclass">
</div>
</div>
</div>
</div>