super11 super11 - 1 year ago 59
Javascript Question

Why is getElementsByTagName not working?

What exactly is wrong with this code?

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

document.getElementsByTagName('P').style.backgroundColor = 'yellow';

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.


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