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
Heh . . . looks like Oscar Jara and I came up with similar ideas around using the JQuery .contents()
method, but ended up with some considerably different implementations:
$(document).ready(function () {
$("#testDiv").contents().each(function() {
var prevNode = this.previousSibling;
var fillerText = "";
while ((prevNode) && ($.trim($(prevNode).text()) === "")) {
fillerText += prevNode.nodeValue;
prevNode = prevNode.previousSibling;
}
if ((prevNode) && (this.nodeType === 1) && (prevNode.nodeType === 1)) {
$(prevNode).text($(prevNode).text() + fillerText + $(this).text());
$(this).remove();
}
});
});
I tested a few different sets of HTML data (three spans back-to-back, spans with spaces in between and without, etc.) all based on your original code, and it seems to work . . . the key was to skip over any "whitespace only" text nodes in between the tags, while preserving any needed spacing that they may have contained.