tags:

views:

46

answers:

5

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've used j.add() to add elements to j, but how do I remove #d1 from j?

j.remove() is not working, because it removes the #d1 and j.length still be 2.

Thanks all! :)

+3  A: 
<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

Kaaviar
+1... and I added a demo..
Reigel
@Reigel Thanks for adding demo
Kaaviar
A: 

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>
FreekOne
Why? It seems a little complex :)
jensgram
For expandability of course, in case the filter ever needs to be more complex. But I do agree, for this particular case the chosen answer does the trick just fine.
FreekOne
A: 
<div id="d1">d1</div>
<div id="d2">d2</div>
<script>
$(function(){
    var j=$("#d1, #d2");

    j.filter(":not( #d1 )")
    j.css("border","1px solid red");
});
</script>
Razor
A: 

The problem is, that the manipulation methods (e.g. add()) does not manipulate the object (collection) in-place but returns an altered collection. Thus, you need to assign the return value from remove() not() back to j:

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

Should be

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

remove() vs. not()

remove() removes the matched set from the DOM (not the set), while not() removes the matched set from the given match leaving the DOM unaltered. I think you're looking for not().

jensgram
A: 

try:

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

if not:

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

jerjer