Javascript Element How to - Get the number inside span nested in a div








Question

We would like to know how to get the number inside span nested in a div.

Answer


<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'>
window.onload=function(){<!--from  w  w w. ja v  a 2 s.  c  om-->

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

}
</script>
</head>
<body>
  <div id="num">
    <span>2</span>
  </div>
</body>
</html>

The code above is rendered as follows: