Question

How can i get the number inside the span?

 <div id="num"><span>2</span></div>

 <script type="text/javascript">
 var nr = document.getElementById('num').innerHTML;
 alert(nr);
 </script>
Was it helpful?

Solution

Try this, Use textContent

var nr = document.getElementById('num').textContent;
alert(nr); //op: 2

OTHER TIPS

Well, you could use textContent to get the text inside the div.

var nr = document.getElementById('num').textContent;

or goto the son span and ask for its content

var nr = document.getElementById('num').childNodes[0].textContent;

If you don't know the other contents of the div, you could use regex to extract only the number from the text

var num = /\d+/.exec(document.getElementById('num').textContent)[0]

Updated : Correct way to get the text inside Span :

 var nrt =  document.getElementById('num'); 
 var nr =nrt.innerText||nrt.textContent;
 alert(nr);

Now it works for all,

Working DEMO

May this will help you..

You can also do:

document.getElementById('num').firstChild.innerHTML

Demo on JSFiddle.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top