The difference between JS children and childnodes

Source: Internet
Author: User
Properties Introduction

Children
Children: Returns a collection of all the immediate child nodes of the parent element, noting that children only returns HTML element nodes, excluding text nodes and attribute nodes.

ChildNodes
childnodes: Returns a collection of all the immediate child nodes of the parent element, noting that unlike children, ChildNodes returns HTML element nodes, attribute nodes, and text nodes. Code Demo

<!
    DOCTYPE html>  

The above code is the output of #test childnodes and children respectively in the console.


The code runs the result diagram as follows:

As you can see, the test.childNodes.length is 7, which includes two text nodes, three HTML element nodes and two return-generated nodes (that is, the #test shown in the console);

Sometimes you need to get the first HTML child node (a non-attribute/text node) of the specified element, and the easiest thing to think about is the FirstChild property. If there is a newline and a space before the first HTML node in the code, then the FirstChild return is not what you want. can use NodeType to judge under.

function GetFirst (elem) {for
    (var i=0,e;e=elem.childnodes[i++];) {
        if (e.nodetype==1) return
            e;
    }
}



The test.children.length is 3, just three HTML element nodes. It should be noted here that children contains annotation nodes in IE.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.