Javascript nodeValue returns null
17,608
Solution 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);
}
Solution 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)
Author by
neonant
Updated on June 14, 2022Comments
-
neonant about 2 years
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..?
-
neonant over 13 yearsThanks..actually double firstchild is kinda weird.
-
Stumpy7 over 11 yearsit's not weird... firstChild is <Text> and the firstChild of <Text> is the textnode itself.
-
GôTô over 9 years@user1473206 do you have a jsfiddle or similar to test this?
-
Alex over 9 yearsI have tried this on ie8 and 9, nodeValue returned as Null
-
solstice333 almost 7 yearsthe text inside the node IS the text node. For instance, for a formatted document like
<foo>\n<bar>baz</bar>\n</foo>
the childNodes property of thefoo
node returnsNodeList [ #text "\n", <bar>, #test "\n" ]