Javascript 将HTML元素的文本获取到数组中

Javascript 将HTML元素的文本获取到数组中,javascript,jquery,html,arrays,algorithm,Javascript,Jquery,Html,Arrays,Algorithm,我有下面的html代码 <!DOCTYPE html> <html> <body> <div> <h1>My First Heading</h1> <p>My first paragraph.</p> </div> <div id="1">

我有下面的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>
如果需要,我可以使用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]);   
  }
} 
如何解决这个问题?

您可以使用
map()
来解决这个问题

$(document).ready(function() {
    var arr = $("#container *").contents().map(function() {
        if (this.nodeType === 3 && this.textContent.trim() != "") {
            return this.textContent.trim();
        }
    });

    console.log(arr);
});
nodeType
对于文本内容将为3

试试这个:

var arr = [];
$(document).find('li,p,h1').each(function(e){
    arr.push(($(this).clone().children().remove().end().text()).trim());
})

你自己试过吗???Shortest:@Kartikeya是的。以下是我拙劣的解决方案<代码>变量根=document.documentElement;递归预序(根);//递归查找和处理所有文本节点函数recursivePreorder(node){//如果节点是文本节点If(node.type==3){//添加到数组}//否则对每个子节点递归else{for(var i=0;它可能有助于循环所有主体元素,并将其推入数组变量$(function(){$('body').find('*').each(function(){});@mplungjan这很好用。但是当我在chrome控制台中运行它时,它给了我一些名为“#text”的元素太好了。如何避免?谢谢你的回答。很抱歉,我没有给我数组。当我记录arr.length时,它输出0。你能帮我解决吗?太好了。链接似乎将文本内容分隔在两侧。如何避免?太好了。链接似乎将文本内容分隔在两侧。如何避免?太好了。链接似乎将文本内容分隔在两侧文本内容在两面。如何避免呢?
$(document).ready(function() {
    var arr = $("#container *").contents().map(function() {
        if (this.nodeType === 3 && this.textContent.trim() != "") {
            return this.textContent.trim();
        }
    });

    console.log(arr);
});
var arr = [];
$(document).find('li,p,h1').each(function(e){
    arr.push(($(this).clone().children().remove().end().text()).trim());
})