AFAIK using a click event and the addEventListener()
should bubble from the innermost element up to the outermost parent element. So what's wrong with the following code?
function ChangeBackground(e){
e.target.style.background = "rgb("+parseInt(Math.random()*256)+","+parseInt(Math.random()*256)+","+parseInt(Math.random()*256)+")";
}
var all= document.querySelectorAll("div,span,p");
for(var i=0; i<all.length;i++){
all[i].addEventListener("click",ChangeBackground);
}
div, span, p{
display: inline-block;
padding: 10px;
border: 1px solid;
}
<span>span
<div>div
<p>p</p>
</div>
<p>p</p>
</span>
<div>div
<div>div
<div>div</div>
</div>
<div>div</div>
</div>
When I click on the p
, it does not change the background of its parent elements.
It does bubble. The problem is in the handler where I referred to the e.target
instead of this
. Heres the corrected code snippet:
(Note that the default background is transparent.)
function ChangeBackground(e){
this.style.background = "rgb("+parseInt(Math.random()*256)+","+parseInt(Math.random()*256)+","+parseInt(Math.random()*256)+")";
}
var all= document.querySelectorAll("div,span,p");
for(var i=0; i<all.length;i++){
all[i].addEventListener("click",ChangeBackground,false);
}
div, span, p{
display: inline-block;
padding: 10px;
border: 1px solid;
}
<span>span
<div>div
<p>p</p>
</div>
<p>p</p>
</span>
<div>div
<div>div
<div>div</div>
</div>
<div>div</div>
</div>