JSFiddle - React, Tailwind, and code Playground
HTML
<div id="test">
Lorem <span class="highlighted">ipsum</span> dolor sit amet, <span class="highlighted">consectetur</span> <span class="highlighted">adipiscing</span> elit. Sed massa.
<div>
JavaScript
function combineSpansIn(selector, spanClass) {
// initialize precedent values
var prec=null;
var precNodeType;
$(selector).contents().each(function(){
if ($.trim( $(this).text() ) !== "") { // empty nodes will be useless here
var nodeType = this.nodeType;
// check if still a combinable span
if (nodeType == 1 && this.className==spanClass && nodeType == precNodeType) {
// append current node to precedent one
$(prec).append(" "+ $(this).text() );
// remove current node
$(this).remove();
} else {
// update precedent values
prec=this;
precNodeType = nodeType;
}
}
});
}
combineSpansIn('#test', 'highlighted');