I have prepared jsFiddle where I want to change background of the div "Child X" by mouse click and if it was clicked again on the already selected div then change the style back to original.
Right now there is a bug when the page just loaded, by the very first click on the child div nothing happens, only if I click second time then the color will be changed. Why ?
P.S. The other functionality should stay as it is, like clicking on the different div, the previous selected div should be unselected
$(".childDiv").click(function () {
const x = document.getElementsByClassName("childDiv");
for (let i = 0; i < x.length; i++) {
x[i].addEventListener("click", function(){
const selectedEl = document.querySelector(".childDivSelected");
if(selectedEl){
selectedEl.classList.remove("childDivSelected");
}
this.classList.add("childDivSelected");
}, false);
}
})
.parentDiv{
border:1px solid black;
padding:10px;
width: 80px;
margin:5px;
display:relative;
}
.childDiv{
border:1px solid blue;
height: 50px;
margin:10px;
}
.childDivSelected{
background-color: #ff0000;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/twitter-bootstrap/2.3.2/js/bootstrap.min.js"></script>
<link href="https://stackpath.bootstrapcdn.com/twitter-bootstrap/2.3.2/css/bootstrap-combined.min.css" rel="stylesheet" />
<div id="divParent1" class="parentDiv">
Group 1
<div id="child1" class="childDiv">
Child 1
</div>
<div id="child2" class="childDiv">
Child 2
</div>
</div>
<div id="divParent2" class="parentDiv">
Group 2
<div id="child1" class="childDiv">
Child 1
</div>
<div id="child2" class="childDiv">
Child 2
</div>
</div>