August 2, 201115 yr Not really a problem just wanting to know if there is a way to stop blank childNodes in js? For example.. html: <html> <head> <meta charset="utf-8"> </head> <body> <div id="parent1"> <div class="child1">1</div> <div class="child2">2</div> <div class="child3">3</div> </div> <div id="result"></div> <script type="text/javascript"> function test(){ var testing = '', childArray = document.getElementById('parent1').childNodes; for(var i in childArray){ testing += childArray[i].className +"<br />"; } document.getElementById('result').innerHTML = testing; } test(); </script> </body> </html> In the result div I seem to end up with a blank node for each newline and also 3 blank nodes at the end. Does anyone know a way of removing them to tidy things up a little or even why JS insists on adding them in the first place?
August 2, 201115 yr According to the DOM spec, text is always held in a textNode. This means that your parent1 div doesn't have 3 children, it has 6. This is probably where your extra children are coming from. To get around this, we usually check the nodeType (a list of the types may be found here) so this piece of code may give you the 3 children you were expecting: <script type="text/javascript"> function test() { var testing = '', childArray = document.getElementById('parent1').childNodes, i; for (i in childArray) { if (childArray[i].nodeType && childArray[i].nodeType === 1) { testing += childArray[i].className + "<br \/>"; } } document.getElementById('result').innerHTML = testing; } </script> Edited August 2, 201115 yr by Skateside
August 3, 201115 yr Author I knew there must be a reason for it but couldn't find it for looking! Thanks very much +1
Create an account or sign in to comment