supersize
supersize

Reputation: 14773

wrap element around span text

I have a span which is filled dynamically. The markup then is

<span class="child">
  John Doe <br>
  [email protected]<br>  
  0123456789<br>
</span>

what I intend to do is wrap another span around the text before the first <br>. It should then be like

<span class="child">
  <span class="firstrow">John Doe</span><br>
  [email protected]<br>  
  0123456789<br>
</span>

How can I detect all text before the first <br> and wrap another span with class around it.

Upvotes: 2

Views: 195

Answers (2)

Avish
Avish

Reputation: 4626

You can use jQuery's .contents method:

// Find what we want to transform
var span = $("span.child");

// The first node in the span's contents would be 
// the text up to the first non-text node, i.e. up to the first <br/>
var firstNode = span.contents().first();

// Wrap it with a span with the class we want
firstNode.wrap("<span.firstrow></span>");

Also see the example in jQuery's documentation, which does something quite similar.

Upvotes: 1

mrk
mrk

Reputation: 5117

Using jQuery, you can use the contents(), first(), and wrap() methods:

$('.child').contents().first().wrap('<span class="firstrow"></span>'); 

A caveat I see with this approach is, I'm using a class selector, not an ID selector, so this code could muck with multiple DOM elements in a page (but that could be what you want also, so it depends on your context).

Upvotes: 9

Related Questions