0

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/

2
  • jsfiddle.net/4Lhn0u87/8 Commented Nov 13, 2014 at 9:41
  • Use find('img').attr('onclick') or find('img')[0].getAttribute('onclick') Commented Dec 2, 2014 at 13:32

2 Answers 2

2

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().

Sign up to request clarification or add additional context in comments.

Comments

0
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.