Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parsing through DOM get all children and values

Tags:

People also ask

How do I get the div element of all children?

If You want to get list only children elements with id or class, avoiding elements without id/class, You can use document. getElementById('container'). querySelectorAll('[id],[class]'); ... querySelectorAll('[id],[class]') will "grab" only elements with id and/or class.

How do I know if my DOM element has children?

To check if an HTML element has child nodes, you can use the hasChildNodes() method. This method returns true if the specified node has any child nodes, otherwise false . Whitespace and comments inside a node are also considered as text and comment nodes.

How do you iterate children in JavaScript?

To iterate over Children of HTML Element in JavaScript, get the reference to this HTML Element, get children of this HTML using using children property, then use for loop to iterate over the children.


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