Div with the id is clicking, the div with class is not clicking. By clicking div I want to change the color. If the color input within the div class is not working, if it is out of div class it works normally. How do I fix this?
var div = document.getElementsByTagName("div");
var divCount = div.length;
var clickedDivId;
for (var i = 0; i < divCount; i += 1) {
div[i].onclick = function(e) {
if (e.target.id) alert(this.id);
clickedDivId = this.id;
e.stopPropagation();
};
}
function BackgroundColor(){
var x = document.getElementsByClassName("backgroundcolor")[0].value;
document.getElementById(clickedDivId).style.backgroundColor = x;
}
#divid{
width: 450px;
height: 170px;
margin: 10px;
padding: 10px;
background-color: blue;
}
.divclass{
width: 450px;
height: 170px;
margin: 10px;
padding: 10px;
background-color: blue;
}
<div class="divclass">
<input type="color" class="backgroundcolor" onchange="BackgroundColor()">
</div>
<div id="divid"></div>
The click event is firing for both divs, but your handler only shows the alert if the clicked
div
has anid
, which the first one doesn't have.You are also using old APIs (
getElementsByTagName
andgetElementsByCalssName
) that should really not be used anymore and the solution is much simpler that what you've done: