Search code examples
javascriptdomgetelementsbytagnameselectors-api

getElementsByTagName does not seem to work


Can someone please explain why my code is not working !!

When I get the element By Id it works perfectly fine. But the same method with getElementsByTagName() does not.

Also if I use querySelector(), it works. However if I use querySelectorAll() the same error returns.

test.html:15 Uncaught TypeError: Cannot set property 'color' of undefined

here is my code:

<DOCTYPE! html>
<html>
<head>

</head>

<body>
<h1>Hello World</h1>
<p id="par">Hello World</p>

<script>
var par = document.getElementById('par');
par.style.color = "red"
var heading = document.getElementsByTagName("h1");
heading.style.color = "red"
</script>


</body>
</html>

Solution

  • enter image description here

    As you can clearly see document,getElementsByTagName returns an array of elements, not a single element.

    So you have to follow proper indexing otherwise it will throw an exception as in your case.