Reputation: 24400
I need to cut a list into two pieces with JQuery. Suppose I have the following list:
<ul>
<li>item</li>
<li>item</li>
<li id="POI">item</li>
<li>item</li>
<li>item</li>
</ul>
I have tried using:
$("li#POI").after("</ul><ul>");
But it seems JQuery thinks I'm creating malformed HTML and does not insert the closing tag. instead it gives me this output:
<ul>
<li>item</li>
<li>item</li>
<li id="POI">item</li>
<ul></ul>
<li>item</li>
<li>item</li>
</ul>
Please advise a way that helps me get the following output with JQuery:
<ul>
<li>item</li>
<li>item</li>
<li id="POI">item</li>
</ul>
<ul>
<li>item</li>
<li>item</li>
</ul>
Many thanks.
Upvotes: 2
Views: 652
Reputation: 98398
This does the trick, for arbitrarily selected li elements.
$('li#POI').each( function () {
$(this).parent().after( $(this).nextAll().wrapAll('<ul/>').parent() )
} )
An example use:
<ul>
<li>item 1</li>
<li>item 2</li>
<li>item 3</li>
<li>item 4</li>
<li>item 5</li>
<li>item 6</li>
<li>item 7</li>
<li>item 8</li>
<li>item 9</li>
<li>item 10</li>
</ul>
<script>
$('ul :nth-child(3n)').each( function () { $(this).parent().after( $(this).nextAll().wrapAll('<ul/>').parent() ) } )
</script>
Upvotes: 1
Reputation: 141879
var splitPoint = $('#POI');
var list = splitPoint.parent();
$('<ul>').append(splitPoint.nextAll()).insertAfter(list);
If your list can be identified by an id or some other selector, then this can be simplified to:
$('<ul>').append($('#POI ~ li')).insertAfter('#listID');
Upvotes: 2
Reputation: 8327
You can use:
var $poi = $('li#POI'),
$ul = $poi.parent(),
$items = $ul.children('li'),
index = $items.index($poi),
$itemsAfterPoi = $items.slice(index + 1);
$('<ul>').append($itemsAfterPoi).insertAfter($ul);
Upvotes: 1