Reputation: 33850
The event.target.id
property returns an empty string in my list item event click handler. Why is that?
$("ol").on("click", "li", function(event) {
let id = event.target.id; // returns ""
});
I know I can get the id
of the list item by using $(this).attr("id")
, but I am just wondering why it is that the piece of code above returns an empty string for the id
?
The event.target is most likely an <li>
since I haven't gotten any other element in the DOM tree between the <ol>
and the <li>
and a bit of reflection says this:
Upvotes: 2
Views: 5455
Reputation: 413712
The event target is not necessarily the <li>
element. Events bubble up the DOM tree.
Thus in:
<ol>
<li>
<span>Hello World!</span>
</ol>
clicking on the text would trigger the event handler but the target would be the <span>
, not the <li>
.
You're using jQuery, so just refer to this
. The library arranges for this
to be a reference to the element relevant to the way the handler was set up.
$(function() {
$("ol").on("click", "li", function(event) {
console.log("event target: ", event.target);
console.log("this.id: ", this.id);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ol>
<li id="the-li-element">
<span id="the-span-element">Hello World!</span>
</ol>
Note also that, ultimately, you'll only get a value for the id attribute of an element if it actually has an id. The browser doesn't make up id attributes for everything in the DOM.
Upvotes: 0
Reputation: 28455
You need to use event.currentTarget
In the below example, if you click on abc, the both the logs paint 2
, however, if you click on def, first logs paint ''
and second logs paint 2
.
$("ol").on("click", "li", function(event) {
console.log(event.target.id);
console.log(event.currentTarget.id);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<ol>
<li id="2">
abc
<span>def</span>
</li>
</ol>
</div>
Upvotes: 7