Element.implement({
// Removes all underlying text nodes
removeTextNodes: function( startNode ){
var initialNode = this || startNode;
var childList = initialNode.childNodes;
if( childList.length === 0 ){ return; }
// Walk through all childNodes. If text - remove, else search/destroy
// potentially underlying text nodes
var currentNode;
var nodesToRemove = [];
for( var i = 0, len = childList.length; i < len; i++ ){
currentNode = childList[i];
if( currentNode.nodeName === '#text' ){ nodesToRemove.push( currentNode ); }
else { Element.removeTextNodes( currentNode ); }
}
// When all text nodes on the current level are found, remove them from the DOM
for( i = 0, len = nodesToRemove.length; i < len ; i++ ){
currentNode = nodesToRemove[i];
currentNode.parentNode.removeChild( currentNode );
}
return this;
}
});
I use this to clear/update a label that only contains a field and text. E.g.
<label id="label-with-field"><input type="radio">Some text<label>
$('label-with-field').removeTextNodes().appendText('newLabel')
The last line in the method, "return this;" makes the method chainable.