How can we use document.querySelectorAll to get all the tags in an html page

Someone suggested I use document.querySelectorAll("#tagContainingWrittenEls > *")to get a link to all the written tags. Then you can iterate through all of them and make .tagNameand .attributesfor each item in the list to get information.

But this can only be done if there is a class called #tagContainingWrittenEls. I thought this was some method

+3
source share
2 answers

The function querySelectorAlltakes a return string NodeList, which can be repeated using 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 selection line is as follows:

  • #nodeid node . tagContainingWrittenEls - , , ( ).
  • > " node".
  • * - "all".

, " node " tagContainingWrittenEls ".

. http://www.w3.org/TR/selectors/#selectors CSS3; ( ) -.

+7

MDN, .querySelectorAll

( ), . - NodeList.


.querySelectorAll , .

CSS: , , , .

CSS, <a> <li>, <ul> id of list red. :

ul#list li a{
    color:red;
}

<a> <li> a <ul> id of list .

, JavaScript <a>

var anchors = document.querySelectorAll('ul#list li a');

anchors NodeList ( ), <a> <li> a <ul> id of list. a NodeList Array, , <a> <li> <ul> id list.


, , , DOM .

+2

All Articles