Javascript nodeValue returns null

China☆狼群 提交于 2019-12-18 21:22:39

问题


Title should make my problem well described.Here goes my code.

<div id="adiv"><text>Some text</text></div>    
<script type="text/javascript">
function vb(){
alert(document.getElementById("adiv").firstChild.nodeValue); //returns null
}
</script>
<input type="button" onclick="vb();" value="get"/>

wheres the problem..?


回答1:


In order to get [merged] text content of an element node:

function vb(){
var textnode = document.getElementById("adiv").firstChild;
alert(textnode.textContent || textnode.innerText);
}

In order to get text content of a text node:

function vb(){
alert(document.getElementById("adiv").firstChild.firstChild.nodeValue);
}



回答2:


You are missing a firstChild:

alert(document.getElementById("adiv").firstChild.firstChild.nodeValue);

(I know it sounds weird but this is how text nodes work)




回答3:


<text> node is not supported in IE 7.



来源:https://stackoverflow.com/questions/3977636/javascript-nodevalue-returns-null

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!