Reputation: 298
I have a div
on my website which contains a number of images. I'm trying to get the onclick
attribute of each of the images inside said div
.
<div class="hoi">
<img src="" onclick="alert('hoi')"/>
<img src="" onclick="alert('hoi')"/>
</div>
I've tried the following Javascript code:
var count = $(".hoi img").length;
for(var i = 0; i <= count; i++){
alert($('.hoi').find('img').getAttribute('onclick'));
}
But I get the following error Uncaught TypeError: undefined is not a function
Here is a fiddle http://jsfiddle.net/4Lhn0u87/7/
Upvotes: 0
Views: 172
Reputation: 209
onclick is a event you can't use it as a data-attribute.use some other.
Here is the working code:
http://jsfiddle.net/silpa/4Lhn0u87/17/
$('.hoi img').each(function(){
$(this).on('click',function(){
alert($(this).attr('data-onclick'));
})
})
I have change onclick to data-onclick and removed alert('hoi') and placed image_1 and image_2 for understanding
Upvotes: 0
Reputation: 388316
There is no method called getAttribute()
in jQuery object, you have .attr(). getAttribute() is a dom api method.
$('.hoi img').each(function(){
console.log($(this).attr('onclick'))
})
Also to iterate through a set of elements you can use .each().
Upvotes: 2