简体   繁体   中英

wrap element around span text

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

<span class="child">
  John Doe <br>
  johndoe@gmail.com<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>
  johndoe@gmail.com<br>  
  0123456789<br>
</span>

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

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).

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.

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