JQuery Selector on Dynamically Added Element
I apologize since this must be an incredibly obvious thing that I'm just somehow missing, but I can't figure out how to coax JQuery in to selecting an element that is manually (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, which is great:
<div id="foo">Hello</div>
<div id="bar">
World!
</div>
Now that's very nice, but 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 JQuery was done watching for such things.
I'm curious how I can coax JQuery in to noticing the existence of new elements created not only in exactly the manner shown here, but in general after the DOM has fully loaded.
I've seen lots of suggestions addressing a possibly related but subtly different issue, wherein the solution is to use .live() 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). Perhaps there's a simple way to accomplish this using live(), but I haven't seen it yet. If there is a solution using live then I'd be most grateful to know what event and what function to trigger!
Again, I apologize for having to ask this since I know it must be something incredibly simple and obvious, but being new to JQuery I'm just somehow missing it.
Thanks for your help!
Disclaimer: HTML and JavaScript included are highly distilled in order to illustrate the question, and have not been tested. There are probably mistakes. If so, please don't let those mistakes distract from the more general question.