Remove DOM elements from jQuery object

Jquery

Jquery Problem Overview


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

Jquery Solutions


Solution 1 - Jquery

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

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'); 

Solution 2 - Jquery

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

var people = $(".people");
people.splice(2,1); // Remove 1 item starting from index 2

Solution 3 - Jquery

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

Filter iterates over the jQuery object collection. For each of the elements: Return true inside filter() to keep the current item in the jQuery object collection. 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 the list-item which has the class 1 and/or 2, in turn removing the last three list-items from the jQuery object collection.


A practical example:

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

This snippet adds a class ("blue") to the unordered list. Then highlights the first two list-items. Then attaches a click-handler to the first two list-items:

$(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!");
    });
});

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionWill PeavyView Question on Stackoverflow
Solution 1 - Jquerygeowa4View Answer on Stackoverflow
Solution 2 - JquerySampsonView Answer on Stackoverflow
Solution 3 - JquerycllpseView Answer on Stackoverflow