简体   繁体   中英

Why can't i access a child node?

Currently learning javascript and I get an error saying 'childNodes [1] is undefined', but (id="intro") has two children, so why can't i access the second child (Hello world!)?

<!DOCTYPE html>
<html>
<body>

<p id="intro">
<h1>DOM Lesson one</h1>
<p>Hello world!</p>
</p>

<script>
try
{
var txt=document.getElementById("intro").childNodes[1].nodeValue;
document.write(txt);
}
catch(err)
{
alert(err);
}
</script>

</body>
</html>

but (id="intro") has two children

It doesn't.

  • You cannot have an h1 element inside a p element
  • The end tag for the p element is optional

Your markup is equivalent to:

<p id="intro">
</p><h1>DOM Lesson one</h1>
<p>Hello world!</p>
</p>

The paragraph has one child node, a text node with spaces/new lines in it.


Even if that wasn't the case (let's try it with a div instead of a paragraph), the white space will still create text nodes, so the node at index 1 will be the h1 element.


You then have another problem, the nodeValue of an element is null .

You need to get the firstChild of the element to get the text node inside it, and then get the nodeValue of that.

<p>元素不能包含<h1>元素,因此childNodes[1]实际上不存在。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM