38

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';
6
  • Because the .style property applies to individual DOM elements, and .getElementsByTagName() returns a list.
    – nnnnnn
    Mar 22, 2017 at 3:10
  • I believe there should be an error throwned, check it
    – wong2
    Mar 22, 2017 at 3:10
  • getElements... note the s at the end of Elements. Use document.getElementsByTagName('body')[0].style['background']
    – slebetman
    Mar 22, 2017 at 3:10
  • getElementsByTagName returns an HTMLCollection, which doesn't have a style property.
    – RobG
    Mar 22, 2017 at 3:11
  • you should take a look at it, it is basic w3schools.com/jsref/dom_obj_style.asp
    – Hua Trung
    Mar 22, 2017 at 3:11

3 Answers 3

64

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

1
  • 2
    Why did you create an obj variable?
    – 4castle
    Dec 30, 2020 at 23:56
7

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
  • Yes, that is a lot simpler. But it doesn't explain why the OP's code doesn't work. (And...green?)
    – nnnnnn
    Mar 22, 2017 at 3:11
  • getElementsByTagName return a object which hold more then one value, you can access it by it's index.
    – Srikrushna
    Mar 22, 2017 at 3:18
3

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

Try this:

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.