Boe*_*oel 1 html javascript jquery
我正在使用 jQuery。我有以下 html 片段:
<h1>Main Title</h1>
<h2>One header</h2>
<p>some text</p>
<p>more text</p>
<ul><li>a list</li></ul>
<h2>Another header</h2>
<a href="######">one link</a>
<h3>ddd</h3>
<p>eee</p>
<h2>Header 3<h2>
<p>This is a Paragraph</p>
Run Code Online (Sandbox Code Playgroud)
我需要获取每个 h2 元素之间的内容,以便执行以下操作:
First Section text
some text
more text
Second section text
one link
ddd
eee
Third section text
This is a Paragraph
Run Code Online (Sandbox Code Playgroud)
我读过这个资源:http : //www.tutorialspoint.com/jquery/jquery-selectors.htm
但仍然无法弄清楚如何做我需要的。
提前致谢!
我建议如下:
$('h2').each(function(){
var self = $(this),
// gets everything between the $(this) and the next 'h2' element:
contents = self.nextUntil('h2'),
/* creates a new div with which to wrap,
and inserts after the current $(this): */
newWrap = $('<div />').insertAfter(self);
// appends the contents to the new div element:
newWrap.append(contents);
});
Run Code Online (Sandbox Code Playgroud)
虽然上述工作,对于其预期用途,并说明 nextUntil()(这绝对是在这种情况下使用的方法),但我不确定如何向您展示如何实现您的目标,因为您似乎已经离开了您的用例/需求相当模糊。
参考: