简体   繁体   中英

How to add a span wrap with jQuery around text that has line breaks in it?

I'm making a bookmarklet and have gotten a bit stuck, I'm trying to wrap a span around some text. Problem is the text has a fair amount of br s in it which is causing me a headache.

Since its a bookmarklet I can only use jQuery to change the HTML. I only want to wrap the text below the mediablock (so I can truncate it) and not the mediablock itself.

Current HTML Structure below:

 <div class="Message"> <div class="MediaBlock"> <h2>name</h2> </div> This is the text <br> I want to wrap <br> With a span, class more &nbsp </div> 

I should have mentioned that along with br's there are links as well, also their are multiple message containers on one page.

The message is also variable length, its user generated

$('.Message').contents().filter(function(i) {
    return (this.nodeType === 3 || this.nodeName.toLowerCase() === 'br') && i!=0;
}).wrapAll('<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