0

I just wanted a button to change some colors. For example I have the background in "wrap" div and some borders in other divs.

#wrap {

    width:100vw;
    height: 100vh;

    margin:0 auto;

    font: italic bold 15px arial, sans-serif;

    background-color: rgb(0, 14, 51);

    overflow-y: scroll;

    background-size: cover;

}
    #middleBarExtra{


        margin-top: 130px;

        height: 1px;
        width:100%;

        border: solid 5px rgb(200, 64, 235);

        border-radius: 30px;

}

How can I change the background color in "wrap" and the border color in "midlleBarExtra", with a function in javascript?

I tried this, but didn't work:

function changeColors(){
    
    document.getElementById("wrap").style.background = "white";

}
5
  • Can you attach your full snippet? Commented Oct 29, 2020 at 18:12
  • document.getElementById("wrap").style.background = "white"; - This is correct Commented Oct 29, 2020 at 18:15
  • How do you call changeColors() ? Commented Oct 29, 2020 at 18:15
  • Did you try document.getElementById("wrap").style.backgroundColor = "white" ? Commented Oct 29, 2020 at 18:17
  • i call in in the body: <button onclick="changeColors()">change</button> Commented Oct 29, 2020 at 18:17

2 Answers 2

2

If you change only styles, it's a better idea to add/remove classes instead of using completely js.

function changeColors(){
    document.getElementById("wrap").classList.toggle("new-styles");
}
#wrap {
   width:100vw;
   height: 100vh;
   margin:0 auto;
   background: rgb(0, 14, 51);
}
#middleBarExtra{
    margin-top: 130px;
    height: 1px;
    width:100%;
    border: solid 5px rgb(200, 64, 235);
    border-radius: 30px;
}
#wrap.new-styles {
   background: rgb(255,255,255);
}
.new-styles #middleBarExtra {
   border-color: red;
}
<button onclick="changeColors()">Change</button>

<div id="wrap">
   <div id="middleBarExtra"></div>
</div>

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

Comments

2
document.getElementById("wrap").style.backgroundColor = "white";

2 Comments

Not working :/, might be something wrong with me calling it? <button onclick="changeColors()">change</button>
Is there an error message? Did you change "...style.background" to ...style.backgroundColor"?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.