2011-11-06 142 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]' –