I thought that this would be rather straightforward, but I think the keywords are just too general so I keep getting query results for things like this and this.
Basical
Well, you can try this...
At least it works perfect when using 2 spans
to merge them like your example (when an "empty" element is present). Otherwise, you will need to think a little to handle the span
that lasts.
(To check what I am talking about just take a look commenting the last line: nextElem.remove()
and check the new div
html).
Live Demo: http://jsfiddle.net/oscarj24/t45MR/
HTML:
Lorem
ipsum
dolor sit amet,
consectetur
adipiscing
elit. Sed massa.
jQuery:
$(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 inner 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();
};
Result: