Javascript nodeValue 返回 null
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3977636/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Javascript nodeValue returns null
提问by neo-nant
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..?
问题在哪里..?
回答by Sergey Ilinsky
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);
}
回答by G?T?
You are missing a firstChild:
你缺少一个 firstChild:
alert(document.getElementById("adiv").firstChild.firstChild.nodeValue);
(I know it sounds weird but this is how text nodes work)
(我知道这听起来很奇怪,但这就是文本节点的工作方式)
回答by unigg
<text>node is not supported in IE 7.
<text>IE 7 不支持节点。

