Search code examples
jquerydetach

Restoring jQuery objects after .detach()


I'm going in circles on this one. I have a list of houses. I want to remove houses that don't match chosen criteria. Each house is contained in an li tag.

I thought I could make a jQuery Object of all the li tags on the page, manipulate it, remove the current li tags from the page and append the new list.

But I'm stuck...

<ul id="items">
<li id="p123">Property 1</li>
<li id="p456">Property 2</li>
<li id="p789">Property 3</li>
</ul>


var $j_object = $("li");
var clone = $j_object.clone();

$('li').detach();

itemToShow = '#p456';

// three options to restore list item
$(itemToShow).appendTo($("#items"));

$($j_object[itemToShow]).appendTo($("#items"));

$($clone[itemToShow]).appendTo($("#items"));

Fiddle: http://jsfiddle.net/cc01euf2/


Solution

  • So, you have a collection of jquery objects via:

    var $j_object = $("li");
    

    Essentially, this is an array like:

    ['li#p123', 'li#p456', 'li#p789'] //made up of elements, not strings obviously
    

    To select a single element from this array, you have to use filter. This does the same thing as find but it searches the top layer only. Whereas find searches the descendants of each element in the collection.

    So,

    $j_object.filter('#p456').appendTo('#items');
    

    Will get the #p456 element and append it to #items.

    Also, note that $j_object still references #p456 even after you append it.

    Demo of adding and removing: http://jsfiddle.net/2Lyudrsj/1/