我有以下的html代碼。將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]
如果needsHow我可以使用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]);
}
}
UPDATE
當我的標籤是<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()!=""; });
如何解決這個問題?
你嘗試過自己的東西??? – 2014-12-03 05:54:24
最短的:http://stackoverflow.com/a/7824394/295783 – mplungjan 2014-12-03 06:00:45
@Kartikeya是的。以下是我糟糕的解決方案。 'var root = document.documentElement; recursivePreorder(root); // Recusively找到並處理所有文本節點 功能recursivePreorder(節點){ //如果節點是一個文本節點 如果(node.type == 3){// 添加到數組 } //別的爲每個子節點遞歸 else { for(var i = 0; i
2014-12-03 06:02:00