how can we use document.querySelectorAll to get all the tags in a html page

dom, javascript

Solution

The `querySelectorAll` function takes a selector string returns a `NodeList` which can be iterated through like an array.

// get a NodeList of all child elements of the element with the given id
var list = document.querySelectorAll("#tagContainingWrittenEls > *");

for(var i = 0; i < list.length; ++i) {
    // print the tag name of the node (DIV, SPAN, etc.)
    var curr_node = list[i];
    console.log(curr_node.tagName);

    // show all the attributes of the node (id, class, etc.)
    for(var j = 0; j < curr_node.attributes.length; ++j) {
        var curr_attr = curr_node.attributes[j];
        console.log(curr_attr.name, curr_attr.value);
    }
}

The breakdown of the selector string is as follows:

- The `#nodeid` syntax refers to a node with the given id. Here, the hypothetical id of `tagContainingWrittenEls` is used -- your id will probably be different (and shorter).

- The `>` syntax means "children of that node".

- The `*` is a simple "all" selector.

Taken all together, the selector string says "select all children of the node with the id of "tagContainingWrittenEls".

See http://www.w3.org/TR/selectors/#selectors for a list of CSS3 selectors; they are quite important (and handy) to advanced Web development.

Problem

Someone suggested me to use `document.querySelectorAll("#tagContainingWrittenEls > *")` to get a reference to all the written tags. Then you can loop over 'em all, and do `.tagName` and `.attributes` on each element in the list to get the info. But This can only be done if there is a class named #tagContainingWrittenEls. I thought this is some method

Original source