user1212520 user1212520 - 6 months ago 41
Javascript Question

JQuery append to dynamic div elements

I have been using JQuery to append objects to divides. However I need to clear a section of the screen completely and append html to newly created layout.

<div class="main"><div class="example"></div></div>

$('.example').append('some code');


Works fine, however

<div class="main"></div>
$('.main').append('<div class="example"></div>');
$('.example').append('some code');


Does not generate anything on screen.

I need to loop though variables to create the new content, so I cannot use one append statement. Any neater ways of doing this would be helpful as I have a lot of append statements.

Answer

Sorry but your example works fine.

$('.main').append('<div class="example"></div>');
$('.example').append('some code');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="main"></div>

Maybe check if your js is in the document ready block.