I have code that suppose to find the first child (div) of a div and than change its content, here is my code:
var headDiv = document.getElementById('sliderContainer');
var childDiv = headDiv.childNodes[0];
childDiv.innerHTML = 'Working';
that seems to not working, what’s the problem here?
live : http://jsbin.com/aqozef/edit#javascript,html,live
the full code :
<!doctype html>
<html>
<head>
<script type="javascript">
function scrollit(){
var headDiv = document.getElementById('sliderContainer');
var childDiv = headDiv.childNodes[0];
childDiv.innerHTML = 'Working';
}
</script>
<style type="text/css">
#sliderContainer{width:100px;height:100px;overflow:hidden;}
.sliderContent{width:100px;height:100px;float:left;}
</style>
</head>
<body>
<div id="sliderContainer">
<div class="sliderContent" style="background-color:blue;">s</div>
<div class="sliderContent" style="background-color:yellow;">a</div>
</div><br/><br/>
<button onclick="scrollit();">scroll it</button>
</body>
</html>
It is likely that the first child node is a text node and not an element node. This is the case, for example, when your HTML looks like this:
The line break after the first
divand the spaces before the second one are one text node.To get the element nodes, use
children[MDN]:Note: IE6 – IE8 include comment nodes in
childrenas well. As long as you have no comments there, it is fine.Alternatively you can traverse the child nodes, looking for the first element node:
Reference:
Node.firstChild,Node.nodeType,Node.nextSibling.If you want to change the value of a text node, you have to change the
nodeValue[MDN] property: