Reputation: 26
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.
Upvotes: 0
Views: 2241
Reputation: 1341
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.
Upvotes: 2