How to save jquery selector for later use

I have the following code ...

$('#item_' + code + ' .delete').hide(); $('#item_' + code + ' .deleting').show(); $('#item_' + code).slideUp(400, function() { $(this).remove(); $('#top .message').html('Item has been deleted'); }); 

I want to save the selector that I use in a variable and use it to perform an operation instead of finding the DOM every time.

So, I keep the selector like this ...

  var saved = $('#item_' + code); 

But how do I change the rest of the code? I am not very familiar with jQuery, so I wonder how this can be done. Will it work ...

 $(saved).(' .delete').hide(); $(saved).(' .deleting').hide(); $(saved).slideUp(400, function() { $(this).remove(); $('#top .message').html('Item has been deleted'); }); 
+6
jquery jquery-selectors
source share
6 answers

I will add another alternative

 $('.delete', saved).hide(); $('.deleting', saved).show() ... 
+5
source share

You can use find() :

 var saved = $('#item_' + code); saved.find('.delete, .deleting').hide(); saved.slideUp(400, function() { $(this).remove(); $('#top .message').html('Item has been deleted'); }); 
+5
source share

You can save it in a variable:

 var myVar = $('#item_' + code + ' .delete').hide(); 

and then if you want to add to it just add to var:

 myVar.css("background","green"); 

which is equivalent to:

 $('#item_' + code + ' .delete').hide().css("background","green"); 
+4
source share

Use the find or children methods that let you apply selectors to the result of a previous query.

eg.

 var saved = $('#item_' + code); saved.find(".delete").hide(); saved.find(".deleting").show(); saved.slideUp(400, function() { $(this).remove(); $('#top .message').html('Item has been deleted'); }); 
+2
source share

Use .each function for saved selection

 var SavedStuff = $(<something>); // other code SavedStuff.each( function (i, element) { $(element).<jquery function>; }); 

For example:

 var SavedStuff = $(".Square"); // save all items with Square class // Other code // Later, add rhomboid to all squares SavedStuff.each( function (i, element) { $(element).addClass("Rhomboid"); }); 
0
source share

Try it...

 var saved = ('#item_' + code); $(saved + ' .delete').hide(); $(saved + ' .deleting').show(); $(saved).slideUp(400, function() { $(this).remove(); $('#top .message').html('Item has been deleted'); }); 
-2
source share

All Articles