Aristov
Aristov

Reputation: 33

Change color on all element using a css class

I try to change color in all elements in class, but I have an error:

Cannot convert undefined or null to object

I have code:

<div class="kolorek" onclick="changeColor('34495e');" style="background-color:#34495e;"></div>

function changeColor(color) {
    var block = document.getElementsByClassName('kafelek');
    with (block.style) {
        backgroundColor = "#" + color;
    }
};

Upvotes: 1

Views: 2306

Answers (3)

Aruna
Aruna

Reputation: 12022

As getElementsByClassName will return HTMLCollection, you have to loop through them to set the color as below.

function changeColor(color) {
        var block = document.getElementsByClassName('kafelek');
        for (var i = 0; i < block.length; i++) {
            block[i].style.backgroundColor = "#" + color;
        }
    };
<div class="kolorek" onclick="changeColor('34495e');" style="background-color:#34495e;">Clickable Div</div>

<div class="kafelek">Another Div</div>

Note: Instead of inline onclick event, you can use addEventListener instead

Upvotes: 1

baao
baao

Reputation: 73241

First of all, using with is not recommended and even forbidden since es5 in strict mode (See the link I posted in the comment above). Secondly you are targeting elements with kafelek as their class, but the class you are showing in your html is kolorek. The third error is that you are trying to set a property on a HTMLCollection, but that doesn't exist. It exists on a single element. You need to refactor your code to the following:

function changeColor(color) {
    var block = document.getElementsByClassName('kolorek');
    Array.prototype.forEach.call(block, function(el) {
        el.style.backgroundColor = '#' + color;
    }
};

Upvotes: 0

Geeky
Geeky

Reputation: 7498

Firstly you are searching for the wrong element and you can access style by using element.style and to change backgroundColor it should be element.style.backgroundColor=color

check this snippet

function changeColor(color) {
  var block = document.querySelector('.kolorek');
  console.log(block.style);
  block.style.backgroundColor = "#"+color;
};
<div class="kolorek" onclick="changeColor('999999');" style="background-color:#34495e;">sdfdsfds</div>

Hope this helps

Upvotes: 0

Related Questions