我得到了一段代码,可以从一个可能包含子元素和父元素的随机数组中移除它们,例如:
<html>
<body>
<div id='1'>
<div id='2'>
<div id='3'>
</div>
<div id='4'>
</div>
</div>
</div>
<div id='5'>
<div id='6'>
</div>
</div>
</body>
</html>
arr = document.getElementsByTagName('div')
// arr: [<div#1>,<div#2>, <div#3>, <div#4>, <div#5>, <div#6>]
那么从这个例子中,我该如何提取子元素:
// arr: [<div#3>, <div#4><div#6>]
或者提取父元素:
// arr: [<div#1>, <div#5>]
目前我正在使用:
function isDescendant(parent, child) {
var node = child.parentNode;
while (node != null) {
if (node == parent) {
return true;
}
node = node.parentNode;
}
return false;
}
function filterArray(arr, parent=true){
newArr = [];
arr.forEach((a)=>{
bool = true
if (parent){
arr.forEach((b)=>{
if (isDescendant(a, b)){
bool = false
};
});
}
else{
arr.forEach((b)=>{
if (isDescendant(b, a)){
bool = false
};
});
}
if(bool){
newArr.push(a)
}
});
return newArr
};
但我相信一定有更好的解决方案,更加高效。你有什么更好的想法吗?
div > div
可以立即摆脱很多父元素。 - charlietflparent.contains(child)
is another way of doingisDescendant(parent, child)
- jspcal