Remove or empty content of elements

jquery

Solution

Recursively loop through all nodes, and remove all children whose `nodeType` property equals 3 (`Node.TEXT_NODE`). jQuery cannot select just text nodes, so this can be done using vanilla JavaScript.

Example:

function removeText(node) {
    if (!node || !node.childNodes || !node.childNodes.length) return;
    for (var i=node.childNodes.length-1; i>=0; --i) {
        var childNode = node.childNodes[i];
        if (childNode.nodeType === 3) node.removeChild(childNode);
        else if (childNode.nodeType === 1) removeText(childNode);
    }   
}

Or, packed in a jQuery plugin:

$.fn.removeText = function() {
    for (var i=this.length-1; i>=0; --i) removeText(this[i]);
    return this;
};

http://jsfiddle.net/hcKsX/

Problem

I have some HTML like this: ``` <div>TEXT <span>SPAN</span> <a href="">LINK</a> </div> ``` I would like to remove the contents of the elements, usually I would do something like this: ``` $('*').empty(); ``` or ``` $('*').contents().empty(); ``` This however will remove/empty the first span and its content which is the div and link. What can I do to preserve the elements while emptying them? So the end result would be: ``` <span> <div></div> <a href=""></a> </span> ``` Please note I'm looking for something 'universal' that can be applied to any HTML. The above is just an example, in reality the HTML structure would contain more data. Example at JsFiddle

Original source

Related problems