JSFiddle - React, Tailwind, and code Playground
by Oscar Jara
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
$(document).ready(function () {
var elem = $('#test');
elem.contents().filter(function(index) {
//Get index of an empty element
if($.trim($(this).text()) === '')
//Merge the previous index span with the next index span texts
mergeSpan(index);
});
//Print new html
alert(elem.html());
});
function mergeSpan(index){
//Get all 'div' elements
var elems = $('#test').contents();
//Get previous and next element according to index
var prevElem = elems.eq(index - 1);
var nextElem = elems.eq(index + 1);
//Concat both texts
var concatText = prevElem.text() + ' ' + nextElem.text();
//Set the new text in the first span
prevElem.text(concatText);
//Remove other span that lasts
nextElem.remove();
};