Suppose I have the following HTML structure:
<test>
<div>
This is a test
</div>
<div>
This is another test
<button>
Button test
</button>
</div>
</test>
Now I use the following jQuery code to replace, for example, 'T':
$("test *").each(function(index, value) {
$(this).html($(this).html().replace(new RegExp('t', "ig"), "<b>t</b>"));
});
However, this leads to the following HTML structure (which is unexpected, see the tag <button>
that breaks my HTML):
<test>
<div>
<b>T</b>his is a <b>t</b>es<b>t</b>
</div>
<div>
<b>T</b>his is ano<b>t</b>her <b>t</b>es<b>t</b>
<bu<b>t</b><b>t</b>on>
Bu<b>t</b><b>t</b>on <b>t</b>es<b>t</b>
</bu<b>t</b><b>t</b>on>
</div>
</test>
What I want to achieve:
<test>
<div>
<b>T</b>his is a <b>t</b>es<b>t</b>
</div>
<div>
<b>T</b>his is ano<b>t</b>her <b>t</b>es<b>t</b>
<button>
Bu<b>t</b><b>t</b>on <b>t</b>es<b>t</b>
</button>
</div>
</test>
Basically, I want to replace inside the whole element, but keep the HTML tags and all the HTML attributes.
source
share