【发布时间】:2014-12-03 05:53:33
【问题描述】:
我有以下 html 代码。
<!DOCTYPE html>
<html>
<body>
<div>
<h1>My First Heading</h1>
<p>My first paragraph.</p>
</div>
<div id="1">
<p id="2">Paragraph First
<ol id="3">
<li id="4">alice
<ul id="31">
<li id="41">bob</li>
<li id="51">foo</li>
<li id="61">grow</li>
</ul>
</li>
<li id="5">coding</li>
<li id="6">fun</li>
</ol>
</p>
</div>
<div>
<p>Paragraph Second</p>
</div>
</body>
</html>
我想将所有元素的文本放入一个数组中(优先顺序横向)。 因此,对于以下示例数组,
[My First Heading, first paragraph, Paragraph First, alice, bob, foo, grow, coding, fun]
如果需要,我可以使用 jQuery。我能做到吗?
我自己的非工作尝试
var root = document.documentElement;
recursivePreorder(root); // Recusively find and handle all text nodes
function recursivePreorder(node) {
// If node is a text node
if (node.type == 3) {
//add to the array
} // else recurse for each child node
else {
for(var i=0; i<node.childNodes.length; i++)
recursivePreorder(node.childNodes[i]);
}
}
更新
当我的标签是 <li id="41">bob<a href="url">link text</a>alice</li> 时,它给了我 [bob, link text, alice] 。但我希望输出为[bob<a href="url">link text</a>alice] 意味着链接工作正常。这是我目前的解决方案,
var arr=$('body').find('*').contents().filter(function () { return this.nodeType === 3&&this.textContent.trim()!=""; });
如何解决这个问题?
【问题讨论】:
-
你自己试过了吗???
-
@Kartikeya 是的。以下是我糟糕的解决方案。
var root = document.documentElement; recursivePreorder(root); // Recusively find and handle all text nodes function recursivePreorder(node) { // If node is a text node if (node.type == 3) { //add to the array } // else recurse for each child node else { for(var i=0; i<node.childNodes.length; i++) recursivePreorder(node.childNodes[i]); } }但它不起作用:) -
这可能有助于遍历所有的body元素,并推入一个数组变量 $(function() { $('body').find('*').each(function () { }); });
-
@mplungjan 效果很好。但是当我在 chrome 控制台中运行它时,它也给了我一些名为“#text”的元素。如何避免?
标签: javascript jquery html arrays algorithm