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.
Basically, I have the following 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>
I'd like to merge adjacent span tags into a single span tag, which means finding spans with only whitespace between them (this could include spaces, tabs and newlines).
The result I'm looking for is this:
<div id="test">
Lorem
<span class="highlighted">ipsum</span>
dolor sit amet,
<span class="highlighted">consectetur adipiscing</span>
elit. Sed massa.
<div>
I've examined the nextUntil
function, but it seems to only return tags, not text. The result, for example, of
$("span.highlighted").nextUntil("span.highlighted").andSelf().text();
is
ipsumconsecteturadipiscing
rather than
ipsum dolor sit amet, consecteturadipiscing
Given two tags, how can I find the text between them?
Dropping down to the DOM lets you see text node contents when checking siblings.
Something like:
function combineSpans(span, nextspan)
{
var follower = span.nextSibling;
var concat = true;
while (follower != nextspan)
{
if (follower.nodeName != '#text')
{
concat = false;
break;
}
var len = follower.data.trim().length;
if (len > 0)
{
concat = false;
break;
}
follower = follower.nextSibling;
}
if (concat)
{
$(span).text($(span).text() + " " + $(follower).text());
$(follower).remove();
}
}
Using this with your HTML in this CodePen.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With