- 我的类名称为
class-1
、class-2
或class-3
- 可以有很多类(不一定是 3 个),但我会知道所有类名称。
- 我不知道 DOM 结构。
- 我只知道有一个类(具有该类的元素)是所有类的父类。
但是我应该如何找到哪个类是父类/高于所有其他已知类?是class-1
,class-2
或 class-3
?
我有这样的 HTML
<div>
<div> Hey nice talking to you </div>
<div> Hey how are you</div>
<div><br/></div>
<div class="class-1">
<div>Hey, are you there?</div>
<div class="class-2">
<div>How was the day</div>
<div class="class-3"><br/></div>
</div>
</div>
</div>
这是我尝试过的东西
_findClass_1(html) {
return Array.from(html.querySelectorAll('.class-1'));
}
_findClass_2(html) {
return Array.from(html.querySelectorAll('.class-2'));
}
_findClass_3(html) {
return Array.from(html.querySelectorAll('.class-3'));
}
// Parser
getNodes(html) {
const parsers = [
this._findClass_1,
this._findClass_2,
this._findClass_3,
];
let quotedNodes = [];
for (const parser of parsers) {
quotedNodes.push(parser(html) || []);
}
// How can I detect here which one was the parent of all?
return quotedNodes;
}
你能帮我吗? 请不要使用 jQuery。
最佳答案
最简单但痛苦的方法是从根节点遍历 DOM,并在任何直接子节点等于列表中多个类之一时立即停止。
const class_list = [];
recursion(element) {
if (element === null) return false;
// If element has one of the class from the list of class then return element.parentNode
const children = element.children;
children.forEach(child => recursion(element));
return false;
}
通过调用启动进程
const parent_node = recursion(document.getElementById('body'));
if (parent_node) // this is the parent that has all the class element children
关于javascript - 如何检测具有类名的元素是父元素/位于所有其他类名称之上?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54407589/