I want to set body's background without jQuery.
jquery : $('body').css('background','red');
Why won't this work in pure JavaScript?
document.getElementsByTagName('body').style['background'] = 'red';
Join Stack Overflow to learn, share knowledge, and build your career.
I want to set body's background without jQuery.
jquery : $('body').css('background','red');
Why won't this work in pure JavaScript?
document.getElementsByTagName('body').style['background'] = 'red';
document.getElementsByTagName('div')[0].style.backgroundColor = 'RED';
<div>sample</div>
There are many ways you can set the background color. But getElementsByTagName does not return a single object. It's a collection of objects
document.body.style.backgroundColor = "green"; // JavaScript
document.getElementsByTagName("body")[0].style.backgroundColor = "green"; // Another one
getElementsByTagName
does not return a single element, but instead a collection.
Try this:
document.getElementsByTagName('body')[0].style.backgroundColor = 'red';
.style
property applies to individual DOM elements, and.getElementsByTagName()
returns a list. – nnnnnn Mar 22 '17 at 3:10getElements...
note thes
at the end ofElements
. Usedocument.getElementsByTagName('body')[0].style['background']
– slebetman Mar 22 '17 at 3:10