Remove all text content from the HTML div, but keep the HTML tags and structure
You can create a function / plugin that will overwrite elements in the top-level element, deleting the found 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 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:
Obviously, you want to remove all text nodes from this element. You can access text nodes using the jQuery.contents function. And you don't need 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> Normal 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 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 an element, repeat this process if(node.nodeType == Node.ELEMENT_NODE) { removeAllText(node); } } } Use it as:
var thing = document.getElementById('thing'); removeAllText(thing); Pretty simple
Another method, just for fun and learning. Tried to do this without using JS native functions, checking element properties ... Surprisingly, this 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 does not consider pure text nodes as children of a container, so we can also use this behavior.
use jquery.empty () method
https://api.jquery.com/empty/ <<Api link for jquery
Example:
<!--input--> <div class="container"> <div class="hello">Hello</div> <div class="goodbye">Goodbye</div> </div> $( ".hello" ).empty(); <!--result--> <div class="container"> <div class="hello"></div> <div class="goodbye">Goodbye</div> </div>