jQuery: how to remove the text but not the children elements
Solution 1:
Best and easy solution to remove all text elements from certain div is
$("#firstDiv").contents().filter(function(){
return (this.nodeType == 3);
}).remove();
Solution 2:
This works for me:
$(elem).html($(elem).html().replace($(elem).text(),''));
This set the html content without the text content, it means that any html tag inside of elem will be keep without changes.
before:
<div>Hello<input type="text" name="username" value="world!"/></div>
after:
<div><input type="text" name="username" value="world!"/></div>
bye
Solution 3:
Here's my idea:
function removeText(element){
var newElement = $('<' + element[0].nodeName + '/>');
for(i=0; i < item.attributes.length; i++) {
newElement.attr(item.attributes[i].name, item.attributes[i].value);
}
element.children().each(function(){
newElement.append(this);
});
element.replaceWith(newElement);
}