without jQuery: how to remove the text but not the children elements




jquery set text without child elements (4)

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

can I remove with jQuery only the text in a node but not the children elements ?

thanks


Best and easy solution to remove all text elements from certain div is

$("#firstDiv").contents().filter(function(){
    return (this.nodeType == 3);
}).remove();

you cannot do that.Unless it is wrapped by an element.


Here's my idea:

function removeText(element){
    var newElement = $('<' + element[0].nodeName + '/>');
    element.children().each(function(){
        newElement.append(this);
    });
    element.replaceWith(newElement);
}




jquery