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.
Your code has a few problems:
window.alert(y[1].innerHTML);outside of yourhere()function.yis defined inside ofhere(), so you can't accessyoutside ofhere(). This is a simple fix: just move thealert()call into your function.<h1>element should not be outside of<body>I've fixed these probelms below:
Also, you don't need to call
window.alert()becausewindow.is implied. This isn't necessarily a problem though.