Search code examples
jqueryhtmltexttagsinnerhtml

How can I replace the text of an HTML tag


I don't know how to call it but let me call it semi-inner text.

Example

<div id='myDiv'>
    This is the semi-inner text
    <div id='other'></div>
    This is the semi-inner text
<div>

I want to remove/replace those This is the semi-inner text using jquery.

How can I do that?


Solution

  • If you only care about child nodes...

    $('#myDiv').contents().filter(function() {
        return this.nodeType == 3
    }).each(function() {
        this.data = this.data.replace(/This is the semi-inner text/g, 'swapped');
    });​
    

    jsFiddle.

    If you want to check all descendant nodes, make the function recurse when it detects an element node (this.nodeType == 1).