Reputation: 13
I've been trying to get my head around this, but can't seem to think straight anymore. I have a structure like this:
<div id="team-101">
<p>Description 1</p>
<p>Description 2</p>
<p>Description 3</p>
<p>Description 4</p>
<ul><li>Some stuff</li></ul>
</div>
<div id="team-202">
<p>Description 1</p>
<p>Description 2</p>
<p>Description 3</p>
<p>Description 4</p>
<ul><li>Some stuff</li></ul>
</div>
(etc.) What I'd like to do is put the second to last text paragraphs into a div that I could then hide/unhide within each main div:
<div id="team-101">
<p>Description 1</p>
<div id="desc-101">
<p>Description 2</p>
<p>Description 3</p>
<p>Description 4</p>
</div>
<ul><li>Some stuff</li></ul>
</div>
I tried something along
$('div[id^=team-]').each(function() {
$('p:first', this).after('<div>');
$('p:last', this).after('</div>');
but the opening div is then closed automatically, and does not contain the following paragraph. This is probably childrens play, and I'm just too dumb.
Upvotes: 1
Views: 109
Reputation: 144709
DOM doesn't work that way, you can't insert opening and closing tags separately, you can select the p
children and wrap all of them with a DIV element using .wrapAll()
method:
$('div[id^=team-]').each(function() {
var n = this.id.replace('team-', '');
$(this).children('p').slice(1).wrapAll('<div id="desc-'+n+'"/>');
});
Upvotes: 3