简体   繁体   中英

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> 

Filter out everything but the text nodes, and wrap them

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

FIDDLE

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM