1

I am trying to use javaScript to change the background colour of my class which is called row, My javascript and html code is listed below but its not working and im not sure what the problem is, any help would be greatly appreciated.

function changeColour() {
    var row = document.getElementsByClassName("row");
    row.style.backgroundColor="black";
}

My html code for the button is listed below.

<input type="button" id="btnColour" value="Change Colour" 
onclick="changeColour();" />

1 Answer 1

1

getElementsByClassName returns a nodeList, an array-like object filled with the matching elements, you have to iterate over that nodeList and set the style on each matching element

function changeColour() {

    var row = document.getElementsByClassName("row");

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

}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.