0

I used the following function to change my "clock website" to a lighter theme.

var light = function() {
    document.getElementsByClassName('themechange').style.color = "black"
    document.getElementsByTagName('body').style.backgroundColor = "white";
};

I get the error in the title when I try to run the function. If you need more code, inspect element here

JakAttk123
  • 73
  • 2
  • 8

3 Answers3

3

Both Document.getElementsByClassName() and Document.getElementsByTagName() return NodeLists objects.

You cannot apply settings directly to a NodeList, you have to iterate through it and apply the settings to each Node.

However for you can use Document.body to reference the body element directly.

Document.getElementsByClassName() is not supported in Internet Explorer 8 but Document.querySelectorAll() is supported.

/*    Select all elements with the class `themechange`
 *    Iterate with a for loop
 *    Set each element's background color to `black`
 *    Set the body's background color to `white`
 */
var light = function() {
    var themeChanges = document.querySelectorAll('.themechange'), themeChange, i;
    for(i = 0; (themeChange = themeChanges[i]); i++) {
        themeChange.style.color = "black"
    }
    document.body.style.backgroundColor = "white";
};
0

The getElementsByClassName function returns a NodeList, not an element. You'll need to use a loop to change the style property of all of the elements in the list instead of trying to access the non-existent style property of the NodeList.

bmceldowney
  • 2,307
  • 13
  • 19
0

Simply loop over the returned object stopping at i == Object.length and access each element at index i.

document.getElementsByClassName('themechange')[0].style.color = "black"
document.getElementsByTagName('body')[0].style.backgroundColor = "white";
Ryan
  • 14,392
  • 8
  • 62
  • 102