Skip to content Skip to sidebar Skip to footer

Why Is Getelementsbytagname Not Working?

What exactly is wrong with this code?

Hello World!

Solution 1:

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

Solution 2:

You can use the browser console to diagnose these kind issues. Your code triggers:

TypeError: document.getElementsByTagName(...).style is undefined

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

That means that whatever comes right before style is either not an object or it's an object but doesn't have a style property. To see what it is:

console.log(document.getElementsByTagName('P'));

You'll see it's an HTMLCollection, which is what documentation for getElementsByTagName says it should be.

In short, you need to pick an element, for instance the first one:

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

Or, to make your code more robust:

var paragraphs = document.getElementsByTagName('P');
if (paragraphs.length>0) {
    paragraphs[0].style.backgroundColor = 'yellow';
}

Solution 3:

getElementsByTagName returns an Object that is iterable as an Array, you can have more one paragraph in your page, so in the first position there will be the first <p> tag that Javascript meets.

So, what you want is:

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

Solution 4:

Alternatively, use document.getElementById('demo') if you only have one element to manipulate. It won't return an array as ids are exclusive to a single element.

Solution 5:

var x = document.getElementsByTagName("P");
    var i;
    for (i = 0; i < x.length; i++) {
      x[i].style.backgroundColor = "yellow";
    }

Post a Comment for "Why Is Getelementsbytagname Not Working?"