簡體   English   中英

在span文本周圍包裹元素

[英]wrap element around span text

我有一個動態填充的span 然后標記是

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

我打算做的是在第一個<br>之前在文本周圍包裹另一個span 它應該是這樣的

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

如何在第一個文本之前檢測所有文本<br>並用它周圍的類包裝另一個文本。

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

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

我用這種方法看到的一個警告是,我使用的是類選擇器,而不是ID選擇器,所以這段代碼可能會破壞頁面中的多個DOM元素(但這也可能是你想要的,所以這取決於你的上下文)。

你可以使用jQuery的.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文檔中的示例,該文檔執行的操作非常相似。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM