Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove an element from jQuery object?

Tags:

jquery

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! :)

like image 890
Koerr Avatar asked Jun 24 '10 08:06

Koerr


2 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

like image 137
Boris Delormas Avatar answered Oct 10 '22 20:10

Boris Delormas


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().

like image 22
jensgram Avatar answered Oct 10 '22 21:10

jensgram