Skip to content
View in the app

A better way to browse. Learn more.

Web Designer Forum

A full-screen app on your home screen with push notifications, badges and more.

To install this app on iOS and iPadOS
  1. Tap the Share icon in Safari
  2. Scroll the menu and tap Add to Home Screen.
  3. Tap Add in the top-right corner.
To install this app on Android
  1. Tap the 3-dot menu (⋮) in the top-right corner of the browser.
  2. Tap Add to Home screen or Install app.
  3. Confirm by tapping Install.

JS ChildNodes

Featured Replies

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?

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 by Skateside

  • 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

Account

Navigation

Search

Search

Configure browser push notifications

Chrome (Android)
  1. Tap the lock icon next to the address bar.
  2. Tap Permissions → Notifications.
  3. Adjust your preference.
Chrome (Desktop)
  1. Click the padlock icon in the address bar.
  2. Select Site settings.
  3. Find Notifications and adjust your preference.