比较父节点和子节点的相似性

Comparing a parent and a child node for similarity

本文关键字:相似性 子节点 父节点 比较      更新时间:2023-09-26

给定以下结构

<p>
  <p>
    <span>
      <span class="a">
        <p>

我想把它变成

<p>
  <span>
    <span class="a">

是的,第一个块无效,我们将忽略它。这只是一个例子。

基本上,我想做的是检查是否需要任何孩子,如果没有,请删除它,保留它的所有孩子。因此,所有<p>都是相同的直接元素,因此只有顶部的元素真正在做任何事情(在我的代码中,我意识到情况并非总是如此)。然而,跨度虽然名称相同,但并不相同,因为一个有class="a",另一个没有类,因此它们都留下来。

我正在寻找的内容的扩展不仅在类名不同时才有效,而且任何可能使其实际上不同的属性都有效。

以为我可以使用 node1.attributes === node2.attributes ,但这不起作用,即使 node1node2 属性的长度为零。此外,node1 === node2node1.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函数,你需要实现它。

您打算如何处理第二遍和第三遍等?你什么时候停止?删除某些节点后,您最终可能会遇到另一个"无效"状态。只是想一想。