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开发者_如何学JAVA>
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! :)
<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
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()
.
<div id="d1">d1</div>
<div id="d2">d2</div>
$(function(){
var j=$("#d1, #d2");
j.filter(":not( #d1 )").css("border","1px solid red");
});
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>
try the following code:
j.find("#d1").remove();
if not:
j.filter("#d1").remove();
精彩评论