Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
225 views
in Technique[技术] by (71.8m points)

javascript - Parsing through DOM get all children and values

Container is a div i've added some basic HTML to.

The debug_log function is printing the following:

I'm in a span!
I'm in a div!
I'm in a
p

What happened to the rest of the text in the p tag ("aragraph tag!!"). I think I don't understand how exactly to walk through the document tree. I need a function that will parse the entire document tree and return all of the elements and their values. The code below is sort of a first crack at just getting all of the values displayed.

    container.innerHTML = '<span>I'm in a span! </span><div> I'm in a div! </div><p>I'm in a <span>p</span>aragraph tag!!</p>';

    DEMO.parse_dom(container);



   DEMO.parse_dom = function(ele)
    {
        var child_arr = ele.childNodes;

        for(var i = 0; i < child_arr.length; i++)
        {
            debug_log(child_arr[i].firstChild.nodeValue);
            DEMO.parse_dom(child_arr[i]);
        }
     }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Generally when traversing the DOM, you want to specify a start point. From there, check if the start point has childNodes. If it does, loop through them and recurse the function if they too have childNodes.

Here's some code that outputs to the console using the DOM form of these nodes (I used the document/HTML element as a start point). You'll need to run an if against window.console if you're allowing non-developers to load this page/code and using console:

recurseDomChildren(document.documentElement, true);

function recurseDomChildren(start, output)
{
    var nodes;
    if(start.childNodes)
    {
        nodes = start.childNodes;
        loopNodeChildren(nodes, output);
    }
}

function loopNodeChildren(nodes, output)
{
    var node;
    for(var i=0;i<nodes.length;i++)
    {
        node = nodes[i];
        if(output)
        {
            outputNode(node);
        }
        if(node.childNodes)
        {
            recurseDomChildren(node, output);
        }
    }
}

function outputNode(node)
{
    var whitespace = /^s+$/g;
    if(node.nodeType === 1)
    {
        console.log("element: " + node.tagName);  
    }else if(node.nodeType === 3)
    {
        //clear whitespace text nodes
        node.data = node.data.replace(whitespace, "");
        if(node.data)
        {
            console.log("text: " + node.data); 
        }  
    }  
}

Example: http://jsfiddle.net/ee5X6/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...