I made a clicking divs. By clicking on the first two dives I get alert (this.id) - some_id1 or some_id2 and this is fine. Clicking the Add Div button creates a new div some_id3, but clicking the new div does not show the alert (this.id), it does not register. I can not figure out why. Any idea?
<style>
#some_id1{
width: 50px;
height: 50px;
margin: 10px;
float: left;
background-color: red;
}
#some_id2{
width: 50px;
height: 50px;
margin: 10px;
float: left;
background-color: red;
}
#some_id3{
width: 50px;
height: 50px;
margin: 10px;
float: left;
background-color: red;
}
#parent{
width: 350px;
height: 150px;
margin: 10px;
padding: 10px;
background-color: blue;
}
#parent2{
width: 150px;
height: 150px;
margin: 10px;
padding: 10px;
background-color: blue;
}
</style>
<button type="button" onclick="AddDiv()" >Add Div</button>
<div id="parent">
<div id="some_id1"></div>
<div id="some_id2"></div>
</div>
<div id="parent2"></div>
<script>
var div = document.getElementsByTagName("div");
var divCount = div.length;
var clickedDivId
for (var i = 0; i < divCount; i += 1) {
div[i].onclick = function(e) {
event.stopPropagation();
clickedDivId = this.id;
alert(this.id);
};
}
function AddDiv(){
var y = document.createElement('div');
y.id = 'some_id3';
document.getElementById("parent").appendChild(y);
}
</script>