Search code examples
javascriptdomtampermonkey

jsDOM cannot change background color by class or tag


I am trying to change the background Color of an element on another website with tamper monkey. However every time I try it sends the error: cannot change background-color of undefined.

I have tried using getElementsByTagName and getElementsByClassName after which I use the style property then backgroundColor of course.

(function() {
    'use strict';

    var x = document.getElementsByClassName("rdw");
    x.style.backgroundColor = "red";

})();

I would like to use getElementsByClassId because I feel in this scenario its more precise.

As stated I get the error cannot change background color of undefined.

I appreciate the help :)


Solution

  • the return value of getElementsByClassName is

    An HTMLCollection providing a live-updating list of every element which is a member of every class in names.

    so, if you have only one element with that class, you should pick the first one :

    x[0].style.backgroundColor = "red";
    

    otherwise you'll have to loop through the elements :

    [...x].forEach(el => el.style.backgroundColor = "red");