JSFiddle - React, Tailwind, and code Playground
HTML
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"></script>
<body>
<div id="First name"></div>
<div id="Last name">First name
<div>
Not a match
First name <input type="text" name="fname">
Last name, Han shot first! Email
<b>Email </b>
</div>
</div>
</body>
CSS
span[data-string] {
color: red;
}
JavaScript
/**
* replace text with <span> according to the wrapList
* @param {Object} $elem jQuery DOM Object of a text node
*/
function replaceText($elem) {
var pattern,
textcontent = $elem.text(),
wrapList = {
"fname": "First name",
"lname": "Last name",
"email": "Email"
};
for (const key in wrapList) {
if (wrapList.hasOwnProperty(key)) {
pattern = new RegExp(wrapList[key], 'g');
// as we do a DOM manipulation, we only want to do it if necessary
if (pattern.test(textcontent)) {
// replace the text node with new text. $& in JS equals $0 in other languages
textcontent = textcontent.replace(pattern,'<span data-string="'+key+'">$&</span>');
}
}
}
// a change has been made
if (textcontent != $elem.text()) {
$elem.replaceWith(textcontent);
}
}
/**
* loop through DOM nodes recursively and call replaceText() on text nodes
* @param {Object} $elem jQuery DOM Object
*/
function replaceRecursive($elem) {
// get the nodeType of the object's DOM node
var nt = $elem.get(0).nodeType;
if (nt === 3) {
// type 3 is a text node: replace the text
replaceText($elem);
} else if(nt === 1) {
// type 1 is a DOM element: loop through the child objects recursively
$elem.contents().each(function () {
replaceRecursive($(this));
});
}
}
// start with the <body> tag
replaceRecursive($('body'));