Dynamically add Div to html page using javascript or jquery

17,828

Solution 1

$("#parent_div").append('<div id="created_div"></div>');

or if you want the newly created <div>-s to appear before the others

$("#parent_div").prepend('<div id="created_div"></div>');

Solution 2

$('#main').after('<div id="created_div"></div>');

Solution 3

$('<div id="created_div"></div>').insertAfter('#main');
Share:
17,828
jardane
Author by

jardane

Updated on July 01, 2022

Comments

  • jardane
    jardane almost 2 years

    I want to have a main div and have the ability to dynamically add new divs at the same level as the main div. Something like this:

    <div id="main"></div>
    <div id="created_div"></div>
    

    Any help would be wonderful

  • Jonathan M
    Jonathan M about 12 years
    Assuming the original <div> was a child of <body>.
  • Zoltan Toth
    Zoltan Toth about 12 years
    @JonathanM Correct. That was an assumption
  • Jonathan M
    Jonathan M about 12 years
    This works universally, regardless of what level the original <div> is on.
  • emphaticsunshine
    emphaticsunshine about 12 years
    There is another function insertAfter. But after performs better than insertAfter