Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set style using pure JavaScript [duplicate]

Tags:

javascript

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';
like image 419
Giala Jefferson Avatar asked Mar 22 '17 03:03

Giala Jefferson


3 Answers

document.getElementsByTagName('div')[0].style.backgroundColor = 'RED';
<div>sample</div>
like image 163
Chinito Avatar answered Nov 20 '22 03:11

Chinito


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

like image 7
Srikrushna Avatar answered Nov 20 '22 05:11

Srikrushna


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

Try this:

document.getElementsByTagName('body')[0].style.backgroundColor  = 'red';
like image 3
Sagar V Avatar answered Nov 20 '22 04:11

Sagar V