I want to set body's background without jQuery.
Jquery code:
$('body').css('background','red');
Why the following code won't 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
See the demo
getElementsByTagName
does not return a single element, but instead a collection.
Try this:
document.getElementsByTagName('body')[0].style.backgroundColor = 'red';
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With