rokky
rokky

Reputation: 59

JQuery wrap each word of string in span if it is not wrapped

I have a string

<div id="title">Lorem <span class="bold">ipsum</span> dolor sit amet</div>

I want to wrap each unwrapped word in #title container with span. The result must be:

<div id="title"><span>Lorem </span><span class="bold">ipsum</span><span> dolor</span><span> sit</span><span> amet</span></div>

What I tried and it didn't work correctly - wraps the first word, but displays the last three words in the same <span>:

$('#title')
        .contents()
        .filter(function() {
            return this.nodeType === 3;
        })
        .wrap( "<span></span>" );

Upvotes: 1

Views: 479

Answers (1)

Pranav C Balan
Pranav C Balan

Reputation: 115212

Since the last three words are content of a single text node you can't do it in this way, instead you have to split and wrap the content. You can use replaceWith() method and return an array of HTML content.

$('#title')
  .contents()
  .filter(function() {
    return this.nodeType === 3;
  }).replaceWith(function() {
    return this.nodeValue.split(/(?=\b\s)/).map(str => `<span>${str}</span>`)
  });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="title">Lorem <span class="bold">ipsum</span> dolor sit amet</div>

Upvotes: 1

Related Questions