JSFiddle - React, Tailwind, and code Playground

by Trifan Alexandru

HTML

<div class="foo">
    Hello, World. <span>Juice.</span>
    <img src="http://placehold.it/50x50" /> Click me.
    <p>I won't respond to clicks.</p>
    I'll respond. Click me if you like.
</div>

CSS

.foo {
    padding: 1em;
    border: 1px solid red;
}

.foo img {
    float: left;
    margin: 0 1em 1em 0;
    transform: translate(2em, 2em);
}

span, p {
    color: #999;
}

JavaScript

var htmlText = $('.foo').text(); //the big divs text
        
        
        var children = $('.foo').children(); //get dom elements so they can be ignored later
        
        $.each(children, function (index, child) {
            var txt = $(child).text().trim(); 
            if (txt != '') { //if a child has text in him
                htmlText = htmlText.replace(txt, 'xxx'); //replace it in the big text with xxx
            }
        });

        
        console.log(htmlText);
        htmlText = htmlText.split("xxx"); //split for xxx make it arrat
        
        var counter = 0; //the part when the text is added
        $.each(htmlText, function (i, el) {
            htmlText[i] = el.trim();
        
            if (htmlText[i] != "") { //if there is something here than it's my text
                htmlText[i] = '<span class="text">' + htmlText[i] + '</span>'; //replace it with a HTML element personalized
                counter++; //mark that you have replaced the text
            } else { // if there is nothing at this point it means that I have a DOM element here
                htmlText[i] = $(children[i - counter])[0].outerHTML; //add the DOM element
            }
        });
        
        if (children.length >= htmlText.length) { //you might have the case when not all the HTML children were added back 
            for (var i = htmlText.length - 1; i < children.length; i++) {
                htmlText[i + 1] = $(children[i])[0].outerHTML; //add them
            }
        }
        
        htmlText = htmlText.join(""); //form a HTML markup from the altered stuff
        
        $('.foo').html(htmlText); // replace the content of the big div
        
        $('.text').on('click', function (data) { //add click support
            alert('ok');
        });