Pete Pete - 10 days ago 6
HTML Question

Can't access a child node in HTML

I'm working on an exercice that deals with nodes. I'm supposed to replace the first child of a string and the second element. The first child, changing "this is" to "very", but changing "special" to "ordinary" doesn't seem to work.
Would someone explain this to me?

<html>
<head>
<title>Page Title</title>
<style>
.red { color : #FF0000 }
.big { font-size: xx-large }
</style>
<script type='text/javascript'>
function f(){
node=document.getElementById('i1');
node.firstChild.nodeValue='Very ';
node.childNodes[1].nodeValue=" ordinary ";
}
</script>
</head>
<body class='big'>
<h5>Making changes</h5>
<p id='i1'>This is <em>special</em> <span class='red'>text</span>.</p>
<p onclick='f();'>Click to change the paragraph</p>
</body>
</html>

ajm ajm
Answer

You're trying to set the nodeValue of an HTMLElement. You cannot do this as the nodeValue for an HTMLElement (your em element) is null.

You will need to set the textContent, innerText, or innerHTML instead.

node.childNodes[1].textContent = " ordinary ";

Why does this work for node's firstChild (changing "This is" to "Very")? It is a textNode, and therefore you can get and set its nodeValue.