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?
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.
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.
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.
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.
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>
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();
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