• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Unable to attach onclick to img added in JS

 
Greenhorn
Posts: 21
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi All,

I've dynamically added some images to the body.
Tried to register a onclick event for all the images, as follows:


setAttribute onclick dint work, so thought I can add a class name and use


which dint work either.
I gave a direct alert in the first attempt and it printed all undefined as I think there are no <img> tags on the HTML page.
If I add images via js, wont document.getElementsById return these.

How can I add the onclick event. Thanks in advance.
 
Ranch Hand
Posts: 15304
6
Mac OS X IntelliJ IDE Chrome
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
If you're doing it while creating the element, you should use



Adding the onclick as an attribute won't work, as you have discovered.

If you're doing it using jQuery after the fact, you need to use the proper syntax:



This will, basically, watch for new elements with a class of people to show up in the dom and register the event. See documentation.
 
Sheriff
Posts: 67747
173
Mac Mac OS X IntelliJ IDE jQuery TypeScript Java iOS
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
If you are using jQuery. why are you using createElement? Why not use jQuery to create the elements? It's a lot easier and more consistent.
 
Kumara SharmaS
Greenhorn
Posts: 21
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks Gregg. I tried giving,

img.className = "people";

and then the jQuery syntax you'd given. It worked!
 
Consider Paul's rocket mass heater.
reply
    Bookmark Topic Watch Topic
  • New Topic