Javascript DOM How to - Get an H1 using getElementsByTagName








Question

We would like to know how to get an H1 using getElementsByTagName.

Answer


<!DOCTYPE html>
<html>
<head>
<title>- jsFiddle demo by albertmatyi</title>
<script type='text/javascript'>
window.onload=function(){<!--  ww w  .j  av a 2  s  .  c om-->
var h1s = document.getElementsByTagName('h1');
console.log(h1s[0].innerHTML);
console.log(h1s[1].innerHTML);
}
</script>
</head>
<body>
  <h1>Hello</h1>
  <p>Text</p>
  <h1>World</h1>
</body>
</html>

The code above is rendered as follows: