target
is the element that was clicked. With your quoted HTML, assuming there's some CSS that makes those divs not zero-height (as they will be without content), it happens that that will always be the element you want to check because there are no descendant elements in your div
s, but from your question I suspect you have descendant elements you haven't shown, for instance:
<div class="play-animation">Some <span>styled</span> text</div>
<div class="play-animation"><img src="2.png"></div>
If the user clicks the span
or img
above, item.target
in your code (item
really should be event
or e
) will be the span
or img
, not the div
.
To find out if the click passed through your div, you use a combination of Element#closest
and Node#contains
:
document.addEventListener('click', function(event) {
var div = event.target.closest(".play-animation");
if (div && this.contains(div)) {
console.log("Click passed through .play-animation");
} else {
console.log("Click didn't pass through .play-animation");
}
});
<div class="play-animation"><span>text in span</span></div>
<div class="play-animation"><span>text in span</span></div>
<div class="play-animation"><span>text in span</span></div>
<div class="play-animation"><span>text in span</span></div>
<div class="play-animation"><span>text in span</span></div>
<span>text in span but not in a .play-animation div</span>
Now, since you're hooking the event on document
, you actually don't need the contains
call:
document.addEventListener('click', function(event) {
var div = event.target.closest(".play-animation");
if (div) {
console.log("Click passed through .play-animation");
} else {
console.log("Click didn't pass through .play-animation");
}
});
<div class="play-animation"><span>text in span</span></div>
<div class="play-animation"><span>text in span</span></div>
<div class="play-animation"><span>text in span</span></div>
<div class="play-animation"><span>text in span</span></div>
<div class="play-animation"><span>text in span</span></div>
<span>text in span but not in a .play-animation div</span>
You would, though, if you were hooking the event on anything but document
(or possibly anything but document
and document.body
).
If, for some reason, you have to support obsolete browsers that don't have Element#closest
, you can handle the loop doing the check yourself, which would also mean you don't need the contains
call because you can fold that check in:
var element = event.target;
while (element) {
if (element.matches(".play-animation")) {
break;
} else if (element === this) {
element = null;
}
}
if (element) {
// `element` is a `.play-animation` element
}