John the Painter
John the Painter

Reputation: 2615

jQuery wrap text in a span before and after br within a paragraph

As the title suggests I am wondering how I can wrap text in a span before and after br within a paragraph.

My HTML is as so...

<div class="blog-container">
  <div class="each-article">
    <p>Text text text <br/> text text text</p>
  </div>
  <div class="each-article">
    <p>Text text text <br/> text text text</p>
  </div>
</div>

And my jQuery, which I thought would work, is

$('.blog-container .each-article p br').before().wrap('<span></span>');

What this gives me is this:

<div class="blog-container">
  <div class="each-article">
    <p>Text text text <br><span></span></br> text text text</p>
  </div>
  <div class="each-article">
    <p>Text text text <br><span></span></br> text text text</p>
  </div>
</div>

Upvotes: 3

Views: 2996

Answers (1)

Jason P
Jason P

Reputation: 27012

Try this:

http://jsfiddle.net/kKfKS/

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

References:

Edit - The trim isn't necessary here. However, it looks like, in some cases (like if a non-text node is the first child), empty space can be treated as a text node. See this fiddle: http://jsfiddle.net/M3knf/

Upvotes: 9

Related Questions