Element Children

  The childNodes property contains all of the immediate children of the element. There is a significant difference between browsers regarding the identification of these nodes. For example, consider the following code:

1 <ul id="myList">
2     <li>Item 1</li>
3     <li>Item 2</li>
4     <li>Item 3</li>
5 <ul>

  When this code is parsed in IE8 and earlier, the <ul> element has three child nodes, one for each of the <li> elements. In all other browsers, the <ul> element has seven elements: three <li> elements and four text nodes representing the white space between <li> elements. It's important to keep these browser differences in mind when navigating children using the childNodes property. Oftentimes, it's necessary to check the nodeType before performing an action, as the following example shows:

1 for (var i=0, len=element.childNodes.length; i<len; i++){
2     if (element.childNodes[i].nodeType == 1){
3         // do processing
4     }
5 }

 

posted @ 2015-05-21 21:07  林大勇  阅读(211)  评论(0编辑  收藏  举报