Set Style Using Pure Javascript [Duplicate]

Set Style Using Pure Javascript [Duplicate]

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

3 Answers

document.getElementsByTagName('div')[0].style.backgroundColor = 'RED';
<div>sample</div>
1

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

2

getElementsByTagName does not return a single element, but instead a collection.

Try this:

document.getElementsByTagName('body')[0].style.backgroundColor  = 'red';
David Miller
Author

David Miller

David Miller brings 15 years of experience in global economics, personal finance strategy, and market dynamics. He specializes in turning complex economic trends into actionable insights for everyday readers.