簡體   English   中英

jQuery包裝結束標記,直到相同的開始標記

[英]jQuery wrap closing tag until the same opening tag

我有這個標記:

<h2>my title here</h2>
Lorem ipsum dolor sit amet
<h2>my title here</h2>
consectetur adipisicing elit quod tempora

我想選擇從結束</h2>到下一個打開的<h2>之間的所有內容,並將其包裝為帶有類的div,例如:

<h2>my title here</h2>
<div class="my-class">Lorem ipsum dolor sit amet</div>
<h2>my title here</h2>
<div class="my-class">consectetur adipisicing elit quod tempora</div>

 var a = $('body').first().contents().filter(function() { return this.nodeType == 3; }).wrap('<div class="my-class">'); console.log(a) 
 .my-class{ color:red } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <h2>my title here</h2> Lorem ipsum dolor sit amet <h2>my title here</h2> consectetur adipisicing elit quod tempora 

做這樣的事情

 $('h2').each(function(idx, elm) { var $elm = $(elm); // select text after h2 var next = $elm[0].nextSibling; var val = next.nodeValue.trim(); // create div , add text to it var $div = $('<div>'); $div.text(val); // remove previously selected text nodes next.remove(); // add divs after h2 $elm.after($div); }); 
 div { color: blue; font-size: 1.8em; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script> <h2>my title here</h2> Lorem ipsum dolor sit amet <h2>my title here</h2> consectetur adipisicing elit quod tempora 

暫無
暫無

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

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