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?
html() is used to set an element's content, any content that was in that element is completely replaced by the new content. Note: To remove the elements without removing data and events, use . detach() instead.
Approach: Select the HTML element which need to remove. Use JavaScript remove() and removeChild() method to remove the element from the HTML document.
By using text-indent: -999px; or a similar method, the text is still there — just not visually there. Use display:none , and the text is gone.
To select all text inside an element such as DIV, we can simply use JavaScript document. createRange() method to create a range, and than using range. selectNodeContents() we can set node range (start and end), after which use selection. addRange() to select the range of the element.
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();
JSFiddle
Reference:
.contents()
.each()
.remove()
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>
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
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