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.
CodePudding user response:
Your code has a few problems:
- You're calling
window.alert(y[1].innerHTML);
outside of yourhere()
function.y
is defined inside ofhere()
, so you can't accessy
outside ofhere()
. This is a simple fix: just move thealert()
call into your function. - 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.