简体   繁体   中英

Append div container with child elements to web page?

I'm trying to create a button that will dynamically add a div container to the webpage, and currently i'm doing that with code that looks like this inside a .click() event:

$("<div id = 'some_id'></div>").appendTo("#somecontainer");

which is working fine for now. However, I know that later on I will be adding more elements inside this div container (up to 3 or 4) so I'm wondering if there's a better, cleaner way to do this. Otherwise I'm thinking that my append statement will start to look something like this:

$("<div id = 'some_id'><div id = '1'><div id = '2'>...</div></div></div>").appendTo("#somecontainer");

which not only seems wrong, but is hard to structure. Any thoughts?

Edit: by the way, these child elements will end up being standard text/icons that are the same across all of these newly created containers, the only thing that is changing will be some inputted text inside.

use

$("#some_id").appendTo("#somecontainer");

read documentation appendTo

DEMO

Updated Demo

if you wanted to make it easier to edit in future, maybe break your various divs into separate objects then bring them together at the end

makes it very verbose but slightly easier to maintain

$('button').click(function() {
    var parent_container = $('<div id="1">Parent Container</div>'),
        section1 = $('<div id="2">Sub Section 1</div>'),
        subsection1 = $('<div id="3">Content within subsection 1</div>'),
        section2 = $('<div id="4">Sub Section 2</div>'),
        subsection2 = $('<div id="5">Content within subsection 2</div>');

    subsection1.appendTo(section1);
    section1.appendTo(parent_container);
    subsection2.appendTo(section2);
    section2.appendTo(parent_container);
    parent_container.appendTo("#somecontainer");
});

http://jsfiddle.net/tzp0fq2q/1/

而是有一种方法可以将DOM元素附加到容器中,如本示例所示

here I have just measured length of elements inside of Container & appending new DOM element based on its length/index

Maybe should write a little function specific to your task: 'wrap x amount of divs with given ids in another div'

Your call would look something like this:

$makeElement(parentId,[id1,id2,id3]);

Your function might be :

$makeElement(pid,arr){
   var i=1,
        $p=$(pid);
    for(i; i<arr.length;i++){
        $p.append($(arr [i]));
    }
    return $p;
}

You could then use it like this:

$('body')
    .append($makeElement('mybox','p1','p2'))
    .find('#p1')
    .append($makeElement('subbox','s1'));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM