Reputation: 2615
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
Reputation: 27012
Try this:
$('.each-article p').each(function() {
$(this).contents().filter(function() {
return this.nodeType == 3;
}).wrap('<span>');
});
References:
contents()
, which selects all children, including text nodes3
)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