Ramon Rodrgz
Ramon Rodrgz

Reputation: 3

Simulate onclick on a img

I want to simulate a onclick function on all images in a page. the problem is each img has a unique onclick call and also the img does not have an ID or class.

Each img is within a div:

<div id="339949822">
<img src="button.png" onclick="addUser('339949822');">
</div>

Upvotes: 0

Views: 94

Answers (2)

c-smile
c-smile

Reputation: 27450

With jquery:

$("img[onclick]").each(function(index, element){
  eval( $(element).attr("onclick") );
});

Upvotes: 0

El Guapo
El Guapo

Reputation: 5781

you could either add a custom attribute to the img tag

<img src="button.png" data-user-id="339949822"/>

Then reference that attribute in the event handler (you'll have the element) via

element.attr("data-user-id")

or you could traverse up the DOM and grab the id from the enclosing div.

Upvotes: 1

Related Questions