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.
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.
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';
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';
}
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';
var x = document.getElementsByTagName("P");
var i;
for (i = 0; i < x.length; i++) {
x[i].style.backgroundColor = "yellow";
}
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.
document.getElementsByTagName
returns an array of elements. Not just one element.
Since array has a length property, you can select specific element like this,
var paragraphs = document.getElementsByTagName;
paragraph1 = paragraphs[0];
paragraph1.style.cssProperty = 'css value';
to select all elements you loop
for(var i = 0; i < paragraphs.length; i++){
paragraph[i].style.cssProperty = 'css value'
}
Inspect these stuff in your web console like this, you can see all element
console.log(document.getElementsByTagName)