Let's say we have two elements: a div
and a
paragraph p
lying inside this div:
<div>
<p></p>
</div>
Get a reference to our div into a variable:
let div = document.querySelector('div');
Let's add some styling to our tags:
div {
padding: 20px;
border: 1px solid red;
}
p {
width: 200px;
height: 200px;
border: 1px solid green;
}
Now let the click handler be hung on the div:
div.addEventListener('click', function() {
console.log('click');
});
Due to the fact that our div has
padding
,
when we click on the div, we can hit the paragraph,
and we can get to a place where this paragraph does
not exist, that is, directly on the div.
At the same time, in the click handler, this
will always point to the element on which the handler
is hung. In our case this is our div:
div.addEventListener('click', function() {
console.log(this); // div
});
However, we can get exactly the tag in which the
event happened. To do this, we can see what is
in event.target
:
div.addEventListener('click', function(event) {
console.log(event.target); // or div, or paragraph
});
You can distinguish between these two options using the conditions:
let div = document.querySelector('div');
div.addEventListener('click', function(event) {
if (event.target.tagName === 'DIV') {
console.log('clicks exactly on the div');
}
if (event.target.tagName === 'P') {
console.log('clicks exactly on the paragraph');
}
});
You can use
matches
instead of tagName
:
let div = document.querySelector('div');
div.addEventListener('click', function(event) {
if (event.target.matches('div')) {
console.log('clicks exactly on the div');
}
if (event.target.matches('p')) {
console.log('clicks exactly on the paragraph');
}
});
Given the following elements:
<div>
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
</ul>
</div>
div, ul, li {
padding: 20px;
}
div {
border: 1px solid red;
}
ul {
border: 1px solid orange;
}
li {
border: 1px solid green;
}
Attach a click handler to the div. In this handler, determine in which of the tags the event fired.