Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery append order

Tags:

jquery

append

For all the simplicity I just cant see why this does not work.

I need to append a div to the body of the document, then a copy of the same div again but hidden, then another div, then a copy of the other same div again but hidden, and so on...

    $.each(myObj.items, function(i, item) {

        // createItem simply finds an html fragment in the document,
        // clones it and returns it
        var $i = createItem(item);

        // add a div first that clears floats - this is needed before every item
        $('body').append('<div class="clear"/>');

        // append a clone of the html fragment
        $('body').append($i.clone());

        // add another div that clears floats
        $('body').append('<div class="clear"/>');

        // append a clone of the html fragment but hide it
        $('body').append($i.clone().addClass('hidden'));

    });

I am expecting:

    <body>
        <div class="clear"/>
        <div class="item">item</div>

        <div class="clear"/>
        <div class="item hidden">item</div>

        <div class="clear"/>
        <div class="item">item</div>

        <div class="clear"/>
        <div class="item hidden">item</div>
        ...
    </body>

but i get..

    <body>
        <div class="clear"/>
        <div class="item">item</div>

        <div class="clear"/>
        <div class="item">item</div>

        <div class="clear"/>
        <div class="item hidden">item</div>

        <div class="clear"/>
        <div class="item">item</div>

        <div class="clear"/>
        <div class="item hidden">item</div>
        ...
    </body>

Why does the first skip?

Edit

My source html is like this:

    <html>
        <body>
            <div class="template hidden">..</div>
        </body>
    </html>

I clone the template div, return it to my function, add a div (class='clear'), then a clone of the returned div, then another div (class='clear') then another clone of the returned div

There are no more than 5 items in my list.

Edit 2

Stupid User Error... the code works fine. I didn't realise that the first line I had was hard coded not auto generated.

Sorry guys... (feel stupid)

like image 906
Alan Alcock Avatar asked Nov 13 '22 23:11

Alan Alcock


1 Answers

Are you cloning an existing set of divs? I.e. you already have one on your page, so your function clones and adds a regular one and then adds another clone as hidden.

like image 195
Brent D Avatar answered Dec 06 '22 05:12

Brent D