Remove DOM elements from jQuery object

jQuery makes it easy to remove nodes from the DOM. But how do you remove DOM elements from a given jQuery object?

+48
jquery
Sep 10 '09 at 12:56
source share
3 answers

If you're talking about removing nodes from a jQuery object, use the filter or not functions. See here for more details .

How to use filter :

 var ps = $('p'); //Removes all elements from the set of matched elements that do //not match the specified function. ps = ps.filter(function() { //return true to keep it, false to discard it //the logic is up to you. }); 

or

 var ps = $('p'); //Removes all elements from the set of matched elements that //do not match the specified expression(s). ps = ps.filter('.selector'); 

How to use not :

 var ps = $('p'); //Removes elements matching the specified expression //from the set of matched elements. ps = ps.not('.selector'); 
+54
Sep 10 '09 at 12:57
source share

As already noted, $.filter() is a great option for filtering data. Also note that the jQuery object can be processed as an array , and as such you can use array methods such as splice() on it.

 var people = $(".people"); people.splice(2,1); // Remove 1 item starting from index 2 
+8
Sep 10 '09 at 13:05
source share
 <ul> <li class="1" /> <li class="2" /> <li class="3" /> <li class="4" /> <li class="5" /> </ul> 

The filter iterates over a collection of jQuery objects. For each of the elements: Return true inside filter() to save the current element in the jQuery collection of objects. Return false to remove the current object from the jQuery object collection.

 $("li").filter(function () { if (this.className == "1" || this.className == "2") return true; return false; }); 

In this case; the anonymous function executed by filter() will return true for a list item that has class 1 and / or 2, in turn removing the last three list items from the jQuery collection of objects.



A practical example:

 <ul> <li class="1" /> <li class="2" /> <li class="3" /> <li class="4" /> <li class="5" /> </ul> 

This snippet adds the class ("blue") to the unordered list. Then the first two lists are highlighted. It then attaches the click handler to the first two elements of the list:

 $(function () { $("ul").addClass("blue").find("li").filter(function () { if (this.className == "1" || this.className == "2") return true; return false; }).addClass("highlight").click(function () { alert("I am highlighted!"); }); }); 
+2
Sep 10 '09 at 13:01
source share



All Articles