super11 super11 - 1 year ago 66
Javascript Question

Why is getElementsByTagName not working?

What exactly is wrong with this code?

<p id="demo">Hello World!</p>

<script>
document.getElementsByTagName('P').style.backgroundColor = 'yellow';
</script>


The background color is not getting changed to yellow.

Answer Source

getElementsByTagName() returns an array of objects. You need to specify the index inorder to apply the style property.

Use

document.getElementsByTagName('p')[0].style.backgroundColor = 'yellow';