Skip to content Skip to sidebar Skip to footer

Set Style Using Pure Javascript

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['ba

Solution 1:

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

Solution 2:

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"; // JavaScriptdocument.getElementsByTagName("body")[0].style.backgroundColor = "green"; // Another one

See the demo

Solution 3:

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

Try this:

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

Post a Comment for "Set Style Using Pure Javascript"