比较父节点和子节点的相似性
Comparing a parent and a child node for similarity
给定以下结构
<p>
<p>
<span>
<span class="a">
<p>
我想把它变成
<p>
<span>
<span class="a">
是的,第一个块无效,我们将忽略它。这只是一个例子。
基本上,我想做的是检查是否需要任何孩子,如果没有,请删除它,保留它的所有孩子。因此,所有<p>
都是相同的直接元素,因此只有顶部的元素真正在做任何事情(在我的代码中,我意识到情况并非总是如此)。然而,跨度虽然名称相同,但并不相同,因为一个有class="a"
,另一个没有类,因此它们都留下来。
我正在寻找的内容的扩展不仅在类名不同时才有效,而且任何可能使其实际上不同的属性都有效。
我以为我可以使用 node1.attributes === node2.attributes
,但这不起作用,即使 node1
和 node2
属性的长度为零。此外,node1 === node2
、node1.isEqualNode(node2)
和node1.isSameNode(node2)
也都失败了。这是正确的,因为它们不是同一个节点。
那么,我怎样才能正确地检查节点是否符合删除条件呢?
另一个例子,当这实际上有用时
<p>
<b>
Some text
<u>that is
<b>bolded</b> <!-- << That <b> is totally useless, and should be removed. -->
</u>
</b>
</p>
请不要使用Jquery。
这就是我最终得到的:
it = doc.createNodeIterator(doc.firstChild, NodeFilter.SHOW_ALL, null, false);
node = it.nextNode();
while(node){
// Remove any identical children
// Get the node we can move around. We need to go to the parent first, or everything will be true
var tempNode = node.parentNode;
// While we haven't hit the top - This checks for identical children
while(tempNode && tempNode !== div && tempNode !== doc){
// If they're the same name, which isn't not on the noDel list, and they have the same number of attributes
if(node.nodeName === tempNode.nodeName && noDel.indexOf(node.nodeName) < 0 && node.attributes.length === tempNode.attributes.length){
// Set flag that is used to determine if we want to remove or not
var remove = true;
// Loop through all the attributes
for(var i = 0; i < node.attributes.length; ++i){
// If we find a mismatch, make the flag false and leave
if(node.attributes[i] !== tempNode.attributes[i]){
remove = false;
break;
}
}
// If we want to remove it
if(remove){
// Create a new fragment
var frag = doc.createDocumentFragment();
// Place all of nodes children into the fragment
while(node.firstChild){
frag.appendChild(node.firstChild);
}
// Replace the node with the fragment
node.parentNode.replaceChild(frag, node);
}
}
// Otherwise, look at the next parent
tempNode = tempNode.parentNode;
}
// Next node
node = it.nextNode();
}
哦,
这将是一个有趣的面试问题!关于解决方案 - 创建一个函数以您喜欢的任何方式遍历 DOM,它接收谓词函数作为参数。然后收集一系列传递谓词的项目,然后进行"修复"。在你的例子中,谓词显然是一些isChildEssential函数,你需要实现它。
您打算如何处理第二遍和第三遍等?你什么时候停止?删除某些节点后,您最终可能会遇到另一个"无效"状态。只是想一想。
相关文章:
- 选择<李>使用普通JavaScript的子节点,而不是孙节点
- js循环遍历单击的元素子节点
- 如何将数据添加到json的子节点
- 删除HTML节点而不删除其子节点
- 如何在javascript DOM api中获取具有给定条件的子节点
- 仅使用某些子节点访问xml中父节点的子节点
- 检测单击子节点并发送槽事件处理程序
- 从 d3.js 中的树中选择节点的子节点
- 访问所选剑道树视图节点的子节点
- 为什么正文标记后的脚本标记在子节点中计数
- 难以获取使用属性选择的节点的子节点
- 使用Javascript设置带有子节点的父节点的类's文本等于.
- 如何确定父节点是否有子节点
- 在没有 jquery 的情况下更改子节点(父节点具有 ID)中的链接文本
- Javascript - 子节点计数
- 在子节点上重复
- 如何在D3.js基于力的标签布局图中获取公共子节点
- 如何访问React中的子节点
- js初学者-如何在比网页中的DOM节点低一个级别上立即解析所有子节点
- 比较父节点和子节点的相似性