super11 super11 - 6 months ago 12
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

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';