0

我正在编写一个 Chrome 扩展程序来将 HTML 页面转换为不同的格式。

如果我使用document.getElementsByTagName("*")并迭代该集合,我可以看到所有标签。但是,这是一个平面表示。我需要检测打开和关闭“事件”,例如 SAX 解析器,以便我的翻译输出保持正确的包含/嵌套。

在 JavaScript 中执行此操作的正确方法是什么?必须手动执行此操作似乎有点尴尬。有没有其他方法可以做到这一点?

为了说明我的意思...

   <html>
       <body>
           <h1>Header</h1>
           <div>
               <p>some text and a missing closing tag
               <p>some more text</p>
           </div>
           <p>some more dirty HTML
        </body>
    <html>

我需要按以下顺序获取事件:

    html open
    body open
    h1 open
    text
    h1 close
    div open
    p open
    text
    p close
    p open
    text
    p close
    div close
    p open
    text
    p close
    body close
    html close

我觉得在我的迭代中跟踪类似 SAX 解析器的事件取决于我。我还有其他选择吗?如果没有,你能指出我的任何示例代码吗?

谢谢!

4

2 回答 2

2

只需遍历每个节点和每个节点的所有子节点。当一个级别的孩子用尽时,标签关闭。

function parseChildren(node) {

    // if this a text node, it has no children or open/close tags
    if(node.nodeType == 3) {
        console.log("text");
        return;
    }

    console.log(node.tagName.toLowerCase() + " open");

    // parse the child nodes of this node
    for(var i = 0; i < node.childNodes.length; ++i) {
        parseChildren(node.childNodes[i]);
    }

    // all the children are used up, so this tag is done
    console.log(node.tagName.toLowerCase() + " close");
}

要遍历整个页面,只需执行parseChildren(document.documentFragment). 您可以用console.log您喜欢的任何行为替换这些语句。

请注意,此代码报告了很多text节点,因为标签之间的空格算作文本节点。为避免这种情况,只需扩展文本处理代码:

    if(node.nodeType == 3) {
        // if this node is all whitespace, don't report it
        if(node.data.replace(/\s/g,'') == '') { return; }

        // otherwise, report it
        console.log("text");
        return;
    }
于 2012-08-18T01:19:51.370 回答
0

我不认为有它的工具,所以你应该只写一些递归函数,你会在其中get first child以某种方式get next nodeget parent等等。

于 2012-08-18T01:08:59.910 回答