Search code examples
javascriptjquerytextword-wrap

How to wrap span around every text part in an element?


I want to wrap a span element around each text part which is not already wrapped by another element.

I have this:

<p>
  text text text text text text text text <span class="f1">f1 text</span> text text text text text text text text text text text text text <span class="f2">f2 text</span> text text text text text text text
</p>

What I want:

<p>
  <span>text text text text text text text text</span><span class="f1">f1 text</span>
  <span>text text text text text text text text text text text text text</span><span class="f2">f2 text</span><span> text text text text text text text</span>
</p>


Solution

  • Filter out everything but the text nodes, and wrap them

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

    FIDDLE