Pete Pete - 5 months ago 51
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?

<title>Page Title</title>
.red { color : #FF0000 }
.big { font-size: xx-large }
<script type='text/javascript'>
function f(){
node.firstChild.nodeValue='Very ';
node.childNodes[1].nodeValue=" ordinary ";
<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>

ajm ajm

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.