Reputation: 3938
I am new in Jquery and I am trying to understand how event delegation work. I am trying this:
$("#32298").on( 'click',function() { // event delegation
alert("df");
var imgs = document.getElementById("32298")[0].src;
alert(imgs);
});
When I click on the image with this Id I get the first alert but it doesn't work the second alert.
What am I doing wrong here? Thank you.
Upvotes: 0
Views: 58
Reputation: 385
you can try this
$("#32298").click( function() {
alert("df");
var imgs = $(this).attr('src');
alert(imgs);
});
Upvotes: 0
Reputation: 943230
If you want to perform event delegation then the second argument of the event handler function needs to be a selector to match the element that matches the one you want to be clicked.
$(document.body).on('click', "#32290", function(event) {
The problem with your code has nothing to do with event delegation. getElementById
returns a single element (an id must be unique in the document), not a HTML Collection. (Compare with getElementsByTagName
and getElementsByClassName
which use the plural Elements.) It won't have a 0
property.
var imgs = document.getElementById("32298").src;
Upvotes: 4
Reputation: 53198
Since you're using jQuery, you can simply use the $(this)
constructor, rather than document.getElementById()
:
$("#32298").on( 'click',function() {
alert("df");
var imgs = $(this).attr('src');
alert(imgs);
});
For what it's worth, this isn't event delegation by the way, it's just an event bound to an element.
If you must use vanilla JS to fetch the src
attribute, you don't need to pass an index to the returned value of getElementById()
, since this function returns a DOMObject, not an array. Update as follows:
$("#32298").on( 'click',function() {
alert("df");
var imgs = document.getElementById("32298").src;
alert(imgs);
});
It's also worth noting that IDs should be unique, so #32298
should reference a single element in the DOM. I don't know whether it's a typo, but it appears that you may have multiple elements with the same ID (since you use the variable name imgs
- i.e. plural).
Upvotes: 3