Error404 Error404 - 7 months ago 14
Javascript Question

How to get the value of a span that contains another span with Javascript?

I have one

tag inside another one.

<span id="count">255<span>words</span></span>

and I would like to get only the value of the first
tag, the value

What I have tried:

var words = document.getElementById('count'); //Gets the <span>

alert(words.value); //undefined --> does not exist for <span> tag
alert(words.innerHTML); //255<span>words</span>
alert(words.innerText); //255words
alert(words.textContent); //255words

And I know I can do:

var storedWords = words.innerText;
storedWords = storedWords.replace('words','');
alert(storedWords); //255

but I would like to do it directly.

Is it possible to retrieve only the value of the first span?


First get the SPAN element, then select it's first child(which is text node) and then get it's value


NOTE: This will return you text and if you want int in integer then you need to parse it using parseInt function with decimal base(base 10).

parseInt(document.getElementById('count').firstChild.nodeValue, 10)