Uncaught ReferenceError: Invalid left-hand side in assignment javascript

I need to set all elements with a specific class to have a certain background-color.

Here is my code:

/*var elements = $(".km-flat");
    var elements1 = $(".km-view");
    var elements2 = $(".km-navbar");
    var elements3 = $(".km-content");
    elements.style.background-color = "red";
    elements1.style.background-color = "red";
    elements2.style.background-color = "red";
    elements3.style.background-color = "red";*/

    var myElements = document.querySelectorAll(".km-content");

    for (var i = 0; i < myElements.length; i++) {
        myElements[i].style.background-color = "red";
    }

As you can see my first attempt was no good and is commented out. My second attempt is saying Uncaught ReferenceError: Invalid left-hand side in assignment javascript.

What syntax should I be using? Thanks.

Answers:

Answer

You cannot use -, say like bellow

myElements[i].style.backgroundColor = "red";

OR

myElements[i].style["background-color"] = "red";

NOTE:- If you will go through the comments bellow, you'll get to know the second way gives some problem in FF.

Answer

Here's the code that works:

var myElements = document.querySelectorAll(".km-content");

for (var i = 0; i < myElements.length; i++) {
    myElements[i].style.backgroundColor = "red";
}

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us Javascript

©2020 All rights reserved.