3

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>
Shikiryu
  • 10,180
  • 8
  • 49
  • 75
John the Painter
  • 2,495
  • 8
  • 59
  • 101

1 Answers1

9

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/

Jason P
  • 26,984
  • 3
  • 31
  • 45
  • 1
    Out of curiousity, what does this line, `&& $.trim(this.textContent).length > 0;` do? – Terry Sep 26 '13 at 21:10
  • actually ended up using this.nodeType !== 1; to select any text that is not wrapped in another element like anchor tags and/or other inner element. But thank you very much Jason, you just saved my day by mentioning it. – Hooman Askari Dec 13 '14 at 07:24