JSFiddle - React, Tailwind, and code Playground

by Taufik Nurrohman

HTML

<div id="test">
    <h1>An article about John</h1>
    <p>The frist paragraph is about John.</p>
    
    <p>The second paragraph contains a <a href="#">link to John's CV</a>.</p>
    
    <p>The second paragraph contains a <a href="#">link to <span>John</span>'s CV</a>.</p>
    
    <div class="comments">
        <h2>Comments to John's article</h2>
        <ul>
            <li>Some user asks John a question.</li>
            <li>John responds.</li>
        </ul>
    </div>
</div>

JavaScript

// jQuery find/replace text without destroying DOM elements

jQuery.fn.textWalk = function( fn ) {
    this.contents().each( jwalk );
    
    function jwalk() {
        var nn = this.nodeName.toLowerCase();
        if( nn === '#text' ) {
            fn.call( this );
        } else if( this.nodeType === 1 && this.childNodes && this.childNodes[0] && nn !== 'script' && nn !== 'textarea' ) {
            $(this).contents().each( jwalk );
        }
    }
    return this;
};

$('#test').textWalk(function() {
    this.data = this.data.replace('John','Peter');
});