user1811367
user1811367

Reputation: 297

Event binding for a dynamically generated element within a dynamically generated element in jQuery

I'm trying to use 'click' on a dynamically generated DOM. I know that I can just use live or on, however my dynamically generated content is within multiple dynamically generated pieces of content and live/on no longer works.

So my code looks something like this but with more elements before El_b:

El_a = document.createElement("li");
El_b = document.createElement("a");
El_b.id = "myEl";
El_a.appendChild(El_b);

Is there a way to make this work?

PS: I've also tried the livequery jQuery plugin.

Upvotes: 0

Views: 110

Answers (2)

Magus
Magus

Reputation: 15104

If you want to bind a function on the click event on El_b, you can just do this :

$(El_b).click(function() {
    // Your code here
});

But you can use on i think. Even if you create multiple DOM elements. You can use the document or the body. Example :

$('body').on('click', 'li a.my_class', function() {
    // Your code here
});

Upvotes: 1

user1726343
user1726343

Reputation:

As far as delegation is concerned, you always have at least one static DOM element available to you, which is the document. If you can't find a closer element to delegate to, delegate to this.

However, delegation seems to be unnecessary here. The entire process of creating your elements and attaching listeners could be condensed to:

var a = $("<li/>").append($("<a/>").attr("id", "myElement")).click(function () {
    alert('hello');
});

If, as you say, you cannot change the object creation, you can still select it by its ID and attach the listener:

$('#myElement').click(function () {
    alert('hello');
});

Also, those are document fragments, not documents proper, and certainly not DOMs.

Upvotes: 1

Related Questions