Javascript nodeValue返回null

neo*_*ant 9 javascript null nodevalue

标题应该让我的问题得到很好的描述.这是我的代码.

<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"/>
Run Code Online (Sandbox Code Playgroud)

这个问题..?

Ser*_*sky 15

为了获得元素节点的[合并]文本内容:

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

为了获取文本节点的文本内容:

function vb(){
alert(document.getElementById("adiv").firstChild.firstChild.nodeValue);
}
Run Code Online (Sandbox Code Playgroud)


GôT*_*ôTô 11

你错过了firstChild:

alert(document.getElementById("adiv").firstChild.firstChild.nodeValue);
Run Code Online (Sandbox Code Playgroud)

(我知道这听起来很奇怪,但这就是文本节点的工作方式)