0

My JS: document.getElementsByClassName('main').style.backgroundColor = '#101521';

My HTML:

<html class= 'main'>
  <head>
    <meta charset="UTF-8">
    <title>Widg-It</title>
  </head>
  <body>
    <span id="close">X</span>
  </body>
</html>

Im trying to make the background of my webpage the color '#101521' using CSS DOM

I run the code and I get the error: "cannot set property of 'backgroundColor' of undefined"

I do not know what this means, and how to make it work.

1 Answer 1

2

document.getElementsByClassName('main') returns a list. You want the first one in the list which is in index 0 therefore need to specify that by using [0] which is the first element in the list [1] is second etc

document.getElementsByClassName('main')[0].style.backgroundColor = '#101521';

also since there will probably be only one html tag or main. i would suggest using getElementsByTagName() or getElementById().

getElementsByTagName()

HTML: <html> ... </html>

JS: document.getElementsByTagName('html')[0].style.backgroundColor = '#101521';

OR

getElementById()

HTML: <html id="main"> ... </html>

JS: document.getElementdById('main').style.backgroundColor = '#101521';

Its up to you which way you want. All 3 methods will work fine. Hope this helps.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.