jQuery makes it easy to remove nodes from the DOM. But how do you remove DOM elements from a given jQuery object?
The remove( expr ) method removes all matched elements from the DOM.
The jQuery empty() method removes the child elements of the selected element(s).
jQuery uses: . append(); and . remove(); functions to accomplish this task. We could use these methods to append string or any other html or XML element and also remove string and other html or XML elements from the document.
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');
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With