I have HTML that I’m inserting dynamically via jQuery
It is a bunch of <p> tags that I want to handle on click.
However the .click completely ignores these tags.
Here’s an exmple of what I’m trying to do
http://jsfiddle.net/cjds/tc2ty/1/
UPDATE
Okay the click is working but I still have a problem with the theory.
NOTE: The issue is that this data will come in after sometime because its fetched via AJAX. Also its likely to change.
So switching the order while correct in the example will not provide solution in the actual application. Any suggestions on how to set a click event for an element that’s not yet present?
There are few problems with your code. First, you’re duplicating an element with the same id, and ids should unique. Then the problem you’re experiencing is because you’re not delegating the click event. When you create a new dynamic element the events that were previously set are not added to the new elements. There are a few ways to make this work.
You can cache the element and add the click event to it before appending it to the DOM:
Or you can attach the events with delegation by using the
onmethod on the closest static parent, that is your wrapper in this case: