在span文本周围包裹元素

时间:2014-05-27 16:50:22

标签: javascript jquery html

我有span动态填充。然后标记是

<span class="child">
  John Doe <br>
  johndoe@gmail.com<br>  
  0123456789<br>
</span>

我打算做的是在第一个span之前在文本周围包裹另一个<br>。它应该像

<span class="child">
  <span class="firstrow">John Doe</span><br>
  johndoe@gmail.com<br>  
  0123456789<br>
</span>

如何在第一个<br>之前检测所有文本,并用其周围的类包装另一个范围。

2 个答案:

答案 0 :(得分:9)

使用jQuery,您可以使用contents()first()wrap()方法:

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

我用这种方法看到的一个警告是,我使用的是类选择器,而不是ID选择器,所以这段代码可能会破坏页面中的多个DOM元素(但这也可能是你想要的,所以这取决于你的背景。)

答案 1 :(得分:1)

您可以使用jQuery&#39; .contents方法:

// 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>");

另请参阅jQuery文档中的示例,该文档执行的操作非常相似。

相关问题