2011-11-06 71 views
1

我有代码,想找到的第一个孩子(DIV)一个div的和不是改变它的内容,这里是我的代码:更改文本

var headDiv = document.getElementById('sliderContainer'); 
var childDiv = headDiv.childNodes[0]; 
childDiv.innerHTML = 'Working'; 

,似乎不工作,有什么问题在这里?

生活:http://jsbin.com/aqozef/edit#javascript,html,live

的完整代码:

<!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> 
+0

请张贴HTML内容以及 – Saket

回答

4

很可能是第一个子节点是文本节点,而不是一个元素节点。这种情况,例如,当你的HTML看起来像这样:

<div> 
    <div> I'm the first element child</div> 
</div> 

第一div后的换行,并在第二个之前的空间是一个文本节点。

要获得元素节点,使用children[MDN]

headDiv.children[0].innerHTML = "Working"; 

注: IE6 - IE8包括children注释节点为好。只要你在那里没有评论,就没关系。


另外,您可以遍历子节点,寻找第一个元素节点:

var child = element.firstChild; 
while(child && child.nodeType !== 1) child = child.nextSibling; 

参考:Node.firstChildNode.nodeType,​​。


如果你想改变一个文本节点的值,你必须改变nodeValue[MDN]属性:

node.nodeValue = "Working"; 
+0

谢谢菲利克斯这正是我正在寻找。 –

+0

不客气:) –

+0

而不是孩子我推荐getElementsByTagName,比如'document.getElementById('sliderContainer')。getElementsByTagName(“div”)[0]' –