Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery Selector on Dynamically Added Element

I can't figure out how to coax JQuery in to selecting an element (not binding handlers) that is dynamically inserted in to the DOM after the page loads.

For example:

If I have HTML:

<div id="bar">
 World!
</div>

Then I create a new element and insert it in to DOM:

var foo = '<div id="foo">Hello</div>';
$("#bar").before(foo);

I end up with this:

<div id="foo">Hello</div>
<div id="bar">
 World!
</div>

Later on I might want to do something different with the element I inserted, using JQuery to manipulate that new element. But if I try to do:

myHappyEl = $("#foo");

Then myHappyEl will be undefined. JQuery doesn't see it, presumably because it go attached after DOM was loaded.

I've seen lots of suggestions addressing a possibly related but subtly different issue, wherein the solution is to use .live()/.on() to attach an event listener when an element comes in to being. That would be brilliant if I wanted to capture a click event or something, but I don't; I want to be able to select the dynamically added element(s).

like image 467
Gustavo Avatar asked Sep 09 '13 13:09

Gustavo


1 Answers

You'll have to assign that variable after the element has been inserted, like so:

var myHappyEl = $("#foo"); //Nothing, it isnt there
var foo = '<div id="foo">Hello</div>';
$("#bar").before($(foo));
myHappyEl = $("#foo");

Otherwise, the element doesn't exist on the page.

like image 153
tymeJV Avatar answered Nov 02 '22 08:11

tymeJV