Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find text between two tags/nodes

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?

like image 510
JDB Avatar asked Jul 15 '13 19:07

JDB


1 Answers

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.

like image 185
Paul Roub Avatar answered Oct 22 '22 13:10

Paul Roub