Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to use JavaScript with HTML to change the background of a specific <div> based on a color <input>?

Q: I am trying to specifically change a div to a chosen color, and not the entire body through JS

When using JS to utilize an input and change the background depending on a user-decided color, the only line of code I see/can get working is document.body.style.backgroundColor = color;

Is there a way to do, say, document.(classNameForADiv).style.backgroundColor = color;? I’m very new to HTML, CSS, and JS so any advice would be appreciated.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

HTML:

         <div class="cell text">
            Background Color Picker:
        </div>
        <div class="cell js">
            <input type="color" id="color_value" name="color_value" value="Black">
            <!---DOUBLE (1 COLOR BOX 1 BUTTON)-->
            <button class="button two" type="button" onclick="changeBackground()">
                Set Color:
            </button>
        </div>

JS:

function changeBackground(){
  let color = document.getElementById('color_value').value;
  document.body.style.backgroundColor = color;
}

This changes the background of the entire Body tag, whereas I’m looking for a solution to change the background of a Div tag.

>Solution :

You have to pick specific division for change division color.

function changeBackground(){
  let color = document.getElementById('color_value').value;
  let division = document.getElementById("cell_text");
  division.style.backgroundColor = color;
}
<div class="cell text" id = "cell_text">
    Background Color Picker:
</div>
<br>
<div class="cell js">
   <input type="color" id="color_value" name="color_value" value="Black">
   <!---DOUBLE (1 COLOR BOX 1 BUTTON)-->
   <button class="button two" type="button" onclick="changeBackground()">
        Set Color:
   </button>
</div>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading