Question

I use jQuery to add some HTML to the DOM. After the insertion I would like to create an eventhandler which is called on keyup and clicks on the link added to el. However, jQuery does not find the a element as it was added after loading the page.

var el = $("#name");
// add content to el
$(document).keyup(function(e) {
    el.find('a').click();
});

How can I update the DOM in el? I know that there is on() (and its predecessors) in jQuery. However, they do not help me as the event is not registered on the added element itself, but on the document and another event just happens on the newly added element. Any ideas on how to solve this?

Was it helpful?

Solution

Thanks to the response of @Johan I was doing further debugging and found the solution:

el.find('a')[0].click();

So the real problem was not the changing DOM but the click() event that apparently can only be applied to a single element and not to a list of only one element.

Some further discussion about click() not firing can be found here: Can I call jquery click() to follow an <a> link if I haven't bound an event handler to it with bind or click already?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top