I want to change the background color when one of the option from given option is selected in javascript?

201 Views Asked by At

I am trying to change the background color of a <div> when someone chooses a color from the drop-down menu. It's a notes taking website and i want people can change color of the notes.

Here is the HTML code:

<select id="mySelect" class="clr-btn" style="text-align:center" onchange="change_color()">
        <option id="red" value="Red">Red</option>
        <option id="green" value="Green">Green</option>
        <option id="blue" value="Blue">Blue</option>
        </select>

Here is the Javascript:

function change_color() {
    console.log("Change-Color");
    let elm1 = document.getElementsByClassName("clr-btn");
    let elm2 = elm1.options[elm1.selectedIndex].value;
    let elm3 = document.getElementByClassName("card-body");
    document.elm3.style.background = elm2;
}

The error is getting is that "Cannot read properties of un-defined" at elm2. I can't get what is undefined in elm2. Can anyone please help me out?

1

There are 1 best solutions below

5
Carsten Massmann On

Here is a fixed version of your script:

document.body.onclick=ev=>{ // delegated click event handler to "select" a card:
 if (ev.target.classList.contains("card-body")){ // works on .card-body elements only!
  ev.target.classList.toggle("sel");
 }
}
document.querySelector("select").onchange = ev => {
  document.querySelectorAll(".card-body.sel").forEach(d=>{
    d.style.backgroundColor = ev.target.value;
    d.classList.remove("sel");
  });
}
div {display:inline-block; width:200px; margin:10px; padding:8px}
.sel {border: 1px solid gray}
<select id="mySelect" class="clr-btn" style="text-align:center">
  <option value="#ffcccc">Red</option>
  <option value="#ccffcc">Green</option>
  <option value="#ccccff">Blue</option>
</select>

<div class="card-body">this is the div to be colored ...</div>
<div>something else - not to be colored</div>
<div class="card-body">and another one ...</div>
<div class="card-body">yet another one,</div>
<div class="card-body">hard to believe - but again a card!</div>
<div class="card-body">and this lst one.</div>