Paulie
Paulie

Reputation: 131

JQuery cant find dynamicly created element

I want to insert html into dynamicly created table (Im using datatables). In document.ready() function, after initialising datatable i put

$("div.menuContainer").html('<select id="dropdownMenu1"> </select>');

and it doesnt work. But if i enter this line in browser console after loading page it works. What to do folks?

Upvotes: 2

Views: 195

Answers (5)

ozil
ozil

Reputation: 7117

you can use datatable fnInitComplete function.

"fnInitComplete": function () {
$("div.menuContainer").html('<select id="dropdownMenu1"> </select>');
}

Upvotes: 0

ivan.mylyanyk
ivan.mylyanyk

Reputation: 2101

You should try to use 'delegate' method on the parent class.

Delegate attaches a handler to one or more events for all elements that match the selector, now or in the future, based on a specific set of root elements.

You may find this answer useful: jQuery trigger delegation as soon as created

Upvotes: 0

dfsq
dfsq

Reputation: 193271

Since rendering of the DataTable is asynchronous operation (assuming that it also needs to fetch some server-side data), you can't just execute your code after table initialization: it's still not rendered and the HTML structure is not ready.

Instead, use DataTables API events. In your case init event should do the trick:

$('.table').on('init.dt', function() {
    $("div.menuContainer").html('<select id="dropdownMenu1"> </select>');
});

Or you can use initComplete callback in table configuration.

Upvotes: 1

Plamen Nikolov
Plamen Nikolov

Reputation: 96

Are you sure div.menuContainer exists?

Try this after dynamic insert:

$("body").find("div.menuContainer").html('<select id="dropdownMenu1"></select>');

Upvotes: 0

Sagar Devkota
Sagar Devkota

Reputation: 1192

Try Accessing static parent and use find

$(use_parent_static_div_id).find(dynamic_element_id);

here parent means parent div of dynamicly created table

Upvotes: 0

Related Questions