Differences between childNodes and children for DOM elements operated by JavaScript

Source: Internet
Author: User

Differences between childNodes and children for DOM elements operated by JavaScript

For DOM elements, children is a sub-Object of the DOM Object type, excluding textnodes invisible between tags. childNodes includes TextNode objects invisible between tags.

Take a look at the tests for children and childNodes in chrome:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

<! DOCTYPE html>

<Html>

<Head>

<Meta charset = "UTF-8">

<Title> Insert title here </title>

</Head>

<Body>

<Div id = "div1" class = "div">

<Span id = "s1" class = "sp" lang = "zh-cn">

</Span>

</Div>

</Body>

<Script type = "text/javascript">

 

Function test (){

Var o = document. getElementById ("div1 ");

Var child = o. children;

Console. log ("div1.children running result :");

For (I = 0; I <child. length; I ++ ){

Console. log (child [I]. tagName );

}

 

Console. log ("");

Child = o. childNodes;

Console. log ("div1.childNodes running result :");

For (I = 0; I <child. length; I ++ ){

Console. log (child [I]. tagName );

}

 

}

 

Test ();

 

</Script>

</Html>


The test results are as follows:

 

1

2

3

4

5

6

7

Div1.children running result:

SPAN

 

Div1.childNodes running result:

Undefined

SPAN

Undefined

There are two undefined nodes in the result of the above childNodes set, which are the textnodes with nodeType = 3.

If you write the HTML code as follows, the results of children and childNodes are no different.

 

1

2

3

<Body>

<Div id = "div1" class = "div"> <span id = "s1" class = "sp" lang = "zh-cn"> </span> </div>

</Body>

No other differences were found in the HTML elements such as document, head, body, and div.

Related Article

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.