Reputation: 23
What I want is to be able to split an ul into two or more pieces, whenever the class "splithere" is matched. Then I need to wrap each part in a container. Like so:
<ul class="someclass">
<li>One</li>
<li>Two</li>
<li>Three</li>
<li class="splithere">Four</li>
<li>Five</li>
<li>Six</li>
<li class="splithere">Seven</li>
<li>Eight</li>
<li>Nine</li>
</ul>
And what I want to end up with this:
<ul class="someclass">
<li class="newclass">
<ul>
<li>One</li>
<li>Two</li>
<li>Three</li>
</ul>
</li>
<li class="newclass">
<ul>
<li class="splithere">Four</li>
<li>Five</li>
<li>Six</li>
</ul>
</li>
<li class="newclass">
<ul>
<li class="splithere">Seven</li>
<li>Eight</li>
<li>Nine</li>
</ul>
</li>
</ul>
I hope someone can help me...
Upvotes: 2
Views: 301
Reputation: 707318
You can do it like this:
$(".someclass .splithere, .someclass li:first").each(function() {
var li = $('<li class="newclass"></li>').insertBefore(this);
var ul = $("<ul>").appendTo(li);
$(this).nextUntil(".splithere")
.add(this)
.appendTo(ul);
});
Working example: http://jsfiddle.net/jfriend00/TTRhc/
Simplified it a little more:
$(".someclass .splithere, .someclass li:first").each(function() {
var li = $('<li class="newclass"><ul></ul></li>').insertBefore(this);
$(this).nextUntil(".splithere").add(this).appendTo(li.find("ul"));
});
Working example: http://jsfiddle.net/jfriend00/bC5J9/
Upvotes: 1
Reputation: 3937
You want something like this:
$('.splithere').each(function(index){
var masterIndex=$('ul.someclass li').index(this),
listObj=$('ul.someclass li:eq(' + masterIndex + ')).add($('ul.someclass li:eq(' + masterIndex +')').nextUntil($('.splithere').eq(index+1)),
wrapper=$('<li class="newclass"><ul>' + listObj + </ul></li>');
$('ul.someclass li:eq(' + masterIndex + ')').add($('ul.someclass li:eq(' + masterIndex + ')').nextUntil($('.splithere').eq(index+1)).replaceWith(wrapper);
})
What this does is: 1. Gets a master index - i.e. the index of this list item within the list 2. creates an object (listObj) that includes this splithere and the list items until the next split here, and wraps them with the ul and li per your desired result 3. Replaces the original list item and its siblings with the new dom structure
I haven't tested it, but this should work.
Upvotes: 0