Javascript DOM How to - Get node value








Question

We would like to know how to get node value.

Answer


<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'>
window.onload=function(){<!--   w ww. j  a  v a 2  s  .co  m-->
var div = document.getElementsByTagName("div")[0];

console.log("nodeValue: " + div.childNodes[0].nodeValue);

var t = "textContent" in document.body ? "textContent" : "innerText";
console.log("Node text: " + div[t]);
}
</script>
</head>
<body>
  <div>
    First(<em>Away from home</em>)
  </div>
  <div>
    Second(<em>Away from home</em>)
  </div>
</body>
</html>

The code above is rendered as follows: