我有这个标记:
<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>
答案 0 :(得分:1)
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
做这样的事情
答案 1 :(得分:0)
$('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