1

I am trying to hide all the divs inside of the container div section exempt the first one.

Here is my html:

<div id="main">
    <div id="first">
        First div
    </div>
    <div id="second">
        Second div
    </div>
    <div id="third">
        Third div
    </div>
</div>

And here is my JavaScript:

function hide(){
    var target = document.getElementById("main"),
        childList = target.childNodes,
        i = 1;
    for( ; i < childList.length; i++){
        if(childList[i].nodeName !== "#text"){
            childList[i].style.display = 'none';
        };
    };
}

It seems that this should work and hide all divs exempt the first one… But it doesn't. It hides all of the elements. There are no errors in the console.

How can I fix this?

Thank you.

Progo
  • 3,452
  • 5
  • 27
  • 44
  • 1
    The first child node is not what you think it is – it is _actually_ the whitespace text node before your first div element. – CBroe Jan 27 '14 at 03:04

1 Answers1

2

You are using childNodes instead of children. In this case you should be using children.

childList = target.children

Have a look to this answer: What is the difference between children and childNodes in JavaScript?

Community
  • 1
  • 1
S. A.
  • 3,714
  • 2
  • 20
  • 31