简体   繁体   中英

jQuery wrap closing tag until the same opening tag

I have this markup:

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

I would like to select all the content between the closing </h2> until the next opening <h2> and wrap it as a div with a class, for example:

<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 

DO something like this

 $('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 

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