javascripthtmlchildrenchild-nodes

Why doesn´t the childNodes work in my JavaScript code?


I just started programming and I wanted to test some of the basic things in JS. I wanted to try using childNodes (saw it in a tutorial). Does anyone know why it doesn't work?

function here() {
  var x = document.body;
  var y = x.childNodes;
}
window.alert(y[1].innerHTML);
<html>
<h1 onclick="here()">
  click here!
</h1>

<body>
  <p>
    Just some text!
  </p>

  <p>
    Another text!
  </p>
</body>

</html>

I searched for a mistake or a typing error but I couldn't find one.


Solution

  • Your code has a few problems:

    1. You're calling window.alert(y[1].innerHTML); outside of your here() function. y is defined inside of here(), so you can't access y outside of here(). This is a simple fix: just move the alert() call into your function.
    2. Your HTML is practically nonsensical. An <h1> element should not be outside of <body>

    I've fixed these probelms below:

    function here() {
      var x = document.body;
      var y = x.childNodes;
      alert(y[1].innerHTML);
    }
    <html>
    <body>
      <h1 onclick="here()">
        click here!
      </h1>
      <p>
        Just some text!
      </p>
    
      <p>
        Another text!
      </p>
    </body>
    </html>

    Also, you don't need to call window.alert() because window. is implied. This isn't necessarily a problem though.