Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove DOM elements from jQuery object

Tags:

jquery

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

like image 224
Will Peavy Avatar asked Sep 10 '09 12:09

Will Peavy


People also ask

Which method removes all matched elements from the DOM?

The remove( expr ) method removes all matched elements from the DOM.

Which jQuery method is used to remove the child elements from the selected element?

The jQuery empty() method removes the child elements of the selected element(s).

How remove and append in jQuery?

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.


2 Answers

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');  
like image 191
geowa4 Avatar answered Sep 23 '22 21:09

geowa4


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 
like image 43
Sampson Avatar answered Sep 26 '22 21:09

Sampson