For example: when we get all li elements under ul. Or when it is the next element of an element. You may encounter this annoying space problem. Of course, these spaces will be automatically filtered in IE browser. FF, on the other hand, is not that hard-working. FF browser will treat these spaces as an element. If you are confused about space elements in the Dom, please run the following code. Use at least two browsers, IE and FF, to test. You will understand everything!
Dom After running this code. You will find that 3. pops up in IE. Pop up in FF7.
- html
- css
- dom< ;/li>
<script> <br>var list = document.getElementById("list"); <br>var list_child = list.childNodes; //Get all in ol The child elements of <br>alert("There are "list_child.length" elements in ol, respectively"); <br>for(var i = 0; i<list_child.length; i ){ <BR>alert(list_child [i].tagName); <BR>} <BR></script>
The above code demonstrates the need Get all child elements in the ol element. And pop up several sub-elements in ol. We can see that ol contains 3 li elements. 3 pops up in IE. This is correct. So why does 7 pop up in FF and Chrome browsers? In fact, when you write code. A space will be formed between the element and the element wrap. (Note: Don’t think that a space will be formed by entering a carriage return. This is wrong. That is to say, the space between elements means that you just change the line hundreds of times. It is also counted as a space) FF and Chrome browsers will not Filter these space elements. So popping up 7 is also correct.
We use the same html structure below. To demonstrate how to filter and remove these space elements.
Dom head>
After running this code. You will find that the results returned in IE, FF, and Chrome are the same.
- html
- css
- dom< ;/li>
<script> <br>function Del_space(elem){ //Function to filter spaces <br>var elem_child = elem.childNodes; //Get all child elements <br>for(var i = 0;i<elem_child.length;i ){ <BR>//If it is a text node and the content only contains spaces, delete the node <BR>if(elem_child[i].nodeName = = "#text" && ! /S/.test(elem_child[i].nodeValue)){ <BR>elem.removeChild(elem_child[i]);//If the element is a space, delete it <BR>} <BR>} <BR>} <BR>Del_space(document.getElementById("list")); //Delete all spaces in ol <BR>var list = document.getElementById("list"); <BR>var list_child = list.childNodes; //Get all child elements in ol <BR>for(var i=0;i<list_child.length;i ){ <BR>alert(list_child[i].tagName); <BR>} <BR></script>
The following method is recommended:
Dom After running this code. You will find that the results returned in IE, FF, and Chrome are the same.
- html
- css
- dom< ;/li>
<script> <br>for(var x=0,list_li = document.getElementById('list').childNodes; x<list_li.length; x ) { <BR>if(list_li[x].nodeType == 1){ <BR>alert(list_li[x].tagName); <BR>} <BR>} <BR></script>
< ;/body>