Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to dynamically insert an element on an element that was dynamically inserted?

Tags:

html

jquery

css

I want to be able to dynamically append to an element that was dynamically appended. If you have this:

<div id="main">

</div>

$(document).ready(function() {
    $('#main').append('<div id="inner"></div>');

    $('#inner').append('<div id="goal"></div>');
});

#goal never gets appended. Is there a jquery function to handle this or how would I do it?

http://jsfiddle.net/jmZY4/

like image 336
Catfish Avatar asked Jan 23 '26 09:01

Catfish


1 Answers

Turn it on its head (live copy — there was a bug in the CSS of your example, btw, two #main rules and no #inner rule):

$(document).ready(function() {
    var inner = $('<div id="inner"></div>');
    inner.appendTo('#main');
    inner.append('<div id="goal"></div>');
});

appendTo is kind of the converse of append.

You can write that more compactly, though (in my view) it's not worth the loss of clarity (live copy):

$(document).ready(function() {
    $('<div id="inner"></div>')
        .appendTo('#main')
        .append('<div id="goal"></div>');
});

Of course, in your precise example, you could just (live copy):

$(document).ready(function() {
    $('#main').append('<div id="inner"><div id="goal"></div></div>');
});

...but I'm guessing you have a reason for doing the two separately.

like image 93
T.J. Crowder Avatar answered Jan 25 '26 00:01

T.J. Crowder



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!