d1
d2

How to remove item from jQuery object?

the code:

<div id="d1">d1</div> <div id="d2">d2</div> <script> $(function(){ var j=$(); j=j.add("#d1"); j=j.add("#d2"); j.remove("#d1");//not this... //alert(j.length); j.css("border","1px solid red"); }); </script> 

I used j.add() to add elements to j , but how to remove #d1 from j ?

j.remove() does not work because it removes #d1 and j.length is still 2.

Thanks to everyone! :)

+7
jquery
source share
5 answers
 <div id="d1">d1</div> <div id="d2">d2</div> <script> $(function(){ var j=$(); j=j.add("#d1"); j=j.add("#d2"); j=j.not("#d1"); //alert(j.length); j.css("border","1px solid red"); }); </script> 

demo

+11
source share

Use the jQuery grep () function:

 <div id="d1">d1</div> <div id="d2">d2</div> <script> $(function(){ var j=$(); j=j.add("#d1"); j=j.add("#d2"); j = jQuery.grep(arr, function(item){ return item != '#d1'; }); j.css("border","1px solid red"); }); </script> 
+1
source share
 <div id="d1">d1</div> <div id="d2">d2</div> 
 $(function(){ var j=$("#d1, #d2"); j.filter(":not( #d1 )").css("border","1px solid red"); }); 
+1
source share

The problem is that the manipulation methods (for example, add() ) do not manipulate the object (collection) in place, but return the modified collection. So you need to assign a return value from remove() not() back to j :

 j.remove("#d1");//not this... 

Must be

 j = j.not("#d1");//not this... 

remove() vs not()

remove() removes the matched set from the DOM (and not from the set), and not() removes the matched set from the given match, leaving the DOM unchanged. I think you are looking for not() .

+1
source share

try the following code:

 j.find("#d1").remove(); 

if not:

 j.filter("#d1").remove(); 
0
source share

All Articles