How to get child of the element?

for example:

<div id=“asd”>
<p>blabla</p>
</div>

the list below wont work

document.getElementById(“asd”).firstChild.style.visibility = “hidden”;

document.getElementById(“asd”).childNodes[0].style.visibility = “hidden”;

im out of ideas XD

any help?

Hi Vincent,

Welcome to the forums!

The problem is that some browsers will treat a newline as the first child inside a <div>.
That is why your code isn’t working.
To see what I mean try running your code with the following HTML (without spaces):

<div id="asd"><p>blabla</p></div>

Anyway, that doesn’t help you much in the real world.
The best thing to do is to use a simple function to get the firstChild, but which ignores textNodes:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>firstChild example</title>
  </head>
  
  <body>
    <div id="asd">
      <p>blabla</p>
    </div>
    
    <script>
      function getFirstChild(el){
        var firstChild = el.firstChild;
        while(firstChild != null && firstChild.nodeType == 3){ // skip TextNodes
          firstChild = firstChild.nextSibling;
        }
        return firstChild;
      }
      
      var asd = document.getElementById("asd");
      getFirstChild(asd).style.visibility = "hidden";
    </script>
  </body>
</html>

Source: http://stackoverflow.com/questions/2299807/element-firstchild-is-returning-textnode-instead-of-an-object-in-ff

Alternatively hide the text nodes as well (assuming you want everything inside the div to be hidden:

ch = document.getElementById("asd").childNodes;
for (i =ch.length-1, i >= 0; i--) ch[i].style.visibility = "hidden";