-2

I would like to change the html tag dynamically in JavaScript.

I have tried using

document.getElementById("html").setAttribute("style", "background: #000000")

but received the following error: Uncaught TypeError: Cannot read property 'setAttribute' of null

How would I go about doing so?

CSS

html {
   background: #FFFFFF;
}
janeeyrea
  • 195
  • 1
  • 1
  • 10
  • 1
    what is the error you got ? – brk Nov 30 '16 at 04:29
  • 1
    is the id of your element "html" or are you trying to access the html tag? – GraveyardQueen Nov 30 '16 at 04:32
  • @user2181397 Uncaught TypeError: Cannot read property 'setAttribute' of null – janeeyrea Nov 30 '16 at 04:33
  • @GraveyardQueen i am trying to access the html tag – janeeyrea Nov 30 '16 at 04:33
  • You need to add more detail here. If you receive an error, always include the error in your question. If you're selecting something from the DOM, it may be useful to see the element you're selecting. @GraveyardQueen's question could have been avoided by doing so. Better questions help us help you get answers. – Yatrix Nov 30 '16 at 04:33

6 Answers6

1

Do this:

document.getElementsByTagName("html")[0].style.backgroundColor = "#000000";`

Although it is possible to add the style attribute with a value to an element with setAttribute method, it is recommended that you use properties of the Style object instead for inline styling, because this will not overwrite other CSS properties that may be specified in the style attribute

Amoolya S Kumar
  • 1,458
  • 9
  • 10
1

You can do this

document.getElementsByTagName("html")[0].style.background = "#000000";
Mairaj Ahmad
  • 14,434
  • 2
  • 26
  • 40
1

You are referring the the html tag rather than an element in the html body, the getElementByID requires a string that is an element id. For example

<p id="myID">text</p>

then you cound do

document.getElementByID('myID').setAttribute('style', 'background: red');

probably first put the element into a variable but I hope this helps.

RGB
  • 31
  • 1
  • 6
0

You have used document.getElementById to find the Html Tag.

You have to use

document.getElementsByTagName

to locate an element By tag Name

For Reference: W3Schools

Yatrix
  • 13,361
  • 16
  • 48
  • 78
Jefferson Swartz
  • 306
  • 3
  • 10
0

You're probably trying to style the html element; but I'm willing to bet that it's not marked up like so:

<html id="html">

...so your selector won't work.

You're probably needing to use this instead (from How do I change the background color with JavaScript?):

document.body.style.background = '#000000'

(Note: targets the body element.)

Community
  • 1
  • 1
cyrotello
  • 757
  • 9
  • 26
0

To do exactly what you wanted (as per the CSS in your question):

document.documentElement.style.setProperty("background","#000000");
user21820
  • 569
  • 8
  • 17