I have 4 divs , each div has few controls and one button .
How to change the backgroud color of div based on button click in that div to grey .
What you are going to need to do first is find all button elements.
var buttons = document.getElementsByTagName("button");
Next, loop through the button elements and add an event listener to each button.
When a button is clicked change the parent's background color to grey.
this.parentElement.style.backgroundColor = "grey";
var buttons = document.getElementsByTagName("button"); for(var i=0; i<buttons.length; i++) { buttons[i].addEventListener("click",function(e) { this.parentElement.style.backgroundColor = "gray"; }) }
hr{ margin:0px; border:none; height:1px; background-color:gray; }
<div> I will change color when you click the button. <button>Click Me</button> </div> <hr/> <div> I will change color too. <button>Click Me</button> </div> <hr/> <div> What about me? <button>Click Me</button> </div>
Well here is a non- bootstrap solution to your quesiton:
You can find a live example here.
HTML:
<div id="1">
<button onclick="button = 1; changecolour();">Click Me</button>
</div>
<div id="2">
<button onclick="button = 2; changecolour();">Click Me</button>
</div>
<div id="3">
<button onclick="button = 3; changecolour();">Click Me</button>
</div>
CSS (optional ((for demo))):
div {
height: 150%;
width: 30%;
display: inline-block;
background-color: lightgreen;
-webkit-box-shadow: 0 3px 4px black;
-moz-box-shadow: 0 3px 4px black;
box-shadow: 0 3px 4px black;
text-align: center;
padding: 5px;
}
Javascript:
var button = "";
function changecolour() {
console.log(button);
document.getElementById(button).style.backgroundColor = "lightgray";
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.