Nol Franklin
Nol Franklin

Reputation: 33

How can I cache each list item child elements for later use?

I'd like to cache and detach each list item "div.title" onload.

Depending on a click function (view1 or view2) the "div.title" would then append to the correct list item again.

Current attempt: http://jsfiddle.net/nolfranklin/KxXcd/7/ (all titles are appending to last list item)

<code>

    <!-- list items -->

    <li class="item-1">
        <img src="image.jpg" />
        <div class="title">Theme One</div>
    </li>
    <li class="item-2">
        <img src="image.jpg" />
        <div class="title">Theme Two</div>
    </li>

/* Cache list items .title */

var title = $('ul').find('.title').detach();

$('a').click(function() {

        // Reattach title to each list item.

        $('ul li').each(function() {
            $(title).appendTo(this);
        });

});

</code>

Upvotes: 2

Views: 254

Answers (2)

Explosion Pills
Explosion Pills

Reputation: 191779

.detach detaches all of the elements simultaneously and stores them in a collection.

There are several ways to get a specific index out of the collection such as brackets [index], or .get:

$('ul li').each(function() {
    $(title.get($(this).index())).appendTo(this);
});

http://jsfiddle.net/ExplosionPIlls/KxXcd/12/

Upvotes: 0

Sushanth --
Sushanth --

Reputation: 55750

Try this

$('a').click(function() {

    // Reattach title to each list item.

    $('ul li').each(function(i) {
        $(this).append(title[i]);
    });

});

Check Fiddle

title here contains two jQuery objects you are appending the objectList at the end of the li..

You need to iterate over the title which you attach them to the li.

Upvotes: 2

Related Questions