JQuery Selector on Dynamically Added Element

Gustavo picture Gustavo · Sep 9, 2013 · Viewed 30.7k times · Source

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).

Answer

tymeJV picture tymeJV · Sep 9, 2013

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.