Remove all text content from HTML div but keep HTML tags and structure
11,869
Solution 1
You can create a function/plugin that will recurse through elements in your top level element, removing any text nodes found:
$.fn.removeText = function(){
this.each(function(){
// Get elements contents
var $cont = $(this).contents();
// Loop through the contents
$cont.each(function(){
var $this = $(this);
// If it's a text node
if(this.nodeType == 3){
$this.remove(); // Remove it
} else if(this.nodeType == 1){ // If its an element node
$this.removeText(); //Recurse
}
});
});
}
$('#toplevel').removeText();
Reference:
Solution 2
Apparently you want to remove all text nodes from the element. You can access text nodes using jQuery.contents
function. And you do not need any recursion. jQuery does it for you:
$(function() {
$("#to-clean, #to-clean *") // selects the element and all element nodes inside it
.contents() // selects all child nodes including tags, comments and text
.filter(function() {
return this.nodeType === Node.TEXT_NODE; // filter text nodes
}).remove(); // boom!
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div id="to-clean">
Here
<a href="#"> is </a>
<p>Text, that I want to</p>
be removed
</div>
Solution 3
Plain javascript, recursive solution:
function removeAllText(element) {
// loop through all the nodes of the element
var nodes = element.childNodes;
for(var i = 0; i < nodes.length; i++) {
var node = nodes[i];
// if it's a text node, remove it
if(node.nodeType == Node.TEXT_NODE) {
node.parentNode.removeChild(node);
i--; // have to update our incrementor since we just removed a node from childNodes
} else
// if it's an element, repeat this process
if(node.nodeType == Node.ELEMENT_NODE) {
removeAllText(node);
}
}
}
Use it like:
var thing = document.getElementById('thing');
removeAllText(thing);
Pretty simple
Solution 4
One more method, just for fun and learning purposes. Tried to do it without using of native JS functions, checking of element properties...Surprisingly, it works.
clones=[];
$('div').children().each(function() {
clones.push($(this).clone().text(''));
});
$('div').empty();
for(i=0;i<clones.length;i++) {
clones[i].appendTo('div');
}
JQuery doesn't count pure text nodes as child elements of container, so we can use this behavior, too.
Author by
Lokomotywa
Updated on June 08, 2022Comments
-
Lokomotywa almost 2 years
I have:
<div> Here <a href="#"> is </a> <p> Text, that I want to </p> be removed </div>
I want:
<div> <a href="#"> </a> <p> </p> </div>
What is the easiest way to remove all text, but keep the HTML Structure?