2011-07-01 15 views
3

的價值我有此Javascript的for循環:JS拿到產生textnode

renderAElements[i] = document.createElement ("a"); 
     renderAElements[i].setAttribute("href", "#"); 
     renderAElements[i].setAttribute("class", "expander"); 
     renderAElements[i].appendChild(expand); 

     alert (renderAElements[i].nodeValue); 

其中擴大創建爲:

var expand = document.createTextNode("+"); 

警報,其目的是要返回的鏈接文本每個創建的元素都返回null。爲什麼是這樣?

+0

使用el.nodeValue 看到這個答案 http://stackoverflow.com/questions/6546924/js-get-value-of-generated-textnode –

回答

4

因爲您試圖獲取元素節點的nodeValue而不是文本節點。

alert (renderAElements[i].firstChild.nodeValue); 
+0

乾杯。在你的答案出現的同時發現問題。 – YsoL8

0

Check this out

<head> 
    <script type="text/javascript"> 
     function GetTextNode() { 
      var textContainer = document.getElementById ("textContainer"); 
      var textNode = textContainer.firstChild; 
      alert (textNode.data); 
     } 
    </script> 
</head> 
<body> 
    <div id="textContainer">This is a simple text in the container.</div> 
    <button onclick="GetTextNode()">Get the contents of the container</button> 
</body> 
1

這是因爲一個元素包含其他元素,而不是一個值。如果你想獲得文本出節點的,你需要做的要麼

renderAElements.childNodes[0].nodeValue 

renderAElements.innerText 
0

試試這個alert (renderAElements[i].firstChild.nodeValue);