[英]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>
到下一个打开的<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
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.