gpt4 book ai didi

javascript - 在 JavaScript 中迭代 DOM 时关闭标签事件

转载 作者:行者123 更新时间:2023-12-02 19:26:19 26 4
gpt4 key购买 nike

我正在编写一个 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 解析器的事件。我还有其他选择吗?如果没有,你能给我一些示例代码吗?

谢谢!

最佳答案

只需遍历每个节点以及每个节点的所有子节点即可。当某个级别的子级耗尽时,标签将关闭。

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;
}

关于javascript - 在 JavaScript 中迭代 DOM 时关闭标签事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12014941/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com