Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery empty() div except for matched elements

Tags:

jquery

Is there a way to empty a div leaving only elements with a specific class name? Or, is there a way to remove all elements within a div leaving only elements with a specified class?

like image 283
Ronal Avatar asked Aug 11 '09 21:08

Ronal


People also ask

Is Empty function in jQuery?

jQuery empty() MethodThe empty() method removes all child nodes and content from the selected elements. Note: This method does not remove the element itself, or its attributes. Tip: To remove the elements without removing data and events, use the detach() method.

What is the difference between Remove and empty methods in jQuery?

remove() – Removes all child elements with selected element. In this method you can restore all data but not event handlers of removed elements from the DOM. All data and events related with elements will be removed. empty() – Removes all content and child elements from the selected element.

How do I check if a div is not empty?

Use the childNodes property to check if a div element is empty. The childNodes property returns a NodeList of the element's child nodes, including elements, text nodes and comments. If the property returns a value of 0 , then the div is empty.

How do I empty a div?

To clear the contents of a div element, set the element's textContent property to an empty string, e.g. div. textContent = '' . Setting textContent on the element removes all of its children and replaces them with a single text node of the provided value.


2 Answers

This should do the trick:

$('#theDiv').find('*').not('.className').remove();

Sample markup:

<div id="theDiv">
    <p>this will be removed</p>
    <p class="className">this will stay</p>
</div>
like image 52
dcharles Avatar answered Sep 20 '22 21:09

dcharles


Here is another option using just jQuery selectors:

$("#theDiv *:not('.className')").remove();

The issue with a method like this and those above is if there are any child elements they will also be removed, for example:

<div id="theDiv">
    <p>this will be removed</p>
    <p class="className"><strong>this will also be removed :(</strong></p>
</div>

The this will also be removed :( text will be removed as well because it is matched the wildcard * and does not have the class className. In order to solve this we would want to only filter direct children of the parent, such as:

$("#theDiv > *:not('.className')").remove();
like image 21
alienriver49 Avatar answered Sep 24 '22 21:09

alienriver49