Using jQuery, I’m trying to group similar items in a list. Here’s what I’m trying to do. Given a list like the following:
<ul>
<li class="foo">Item #1</li>
<li class="foo">Item #2</li>
<li class="foo">Item #3</li>
<li class="bar">Item #4</li>
<li class="bar">Item #5</li>
<li class="foo">Item #6</li>
<li class="foo">Item #7</li>
<li class="bar">Item #8</li>
</ul>
I’d like to end up with the following:
<ul>
<li class="foo">Item #1 <a>2 More Like This</a>
<ul>
<li class="foo">Item #2</li>
<li class="foo">Item #3</li>
</ul>
</li>
<li class="bar">Item #4</li>
<li class="bar">Item #5</li>
<li class="foo">Item #6 <a>1 More Like This</a>
<ul>
<li class="foo">Item #7</li>
</ul>
</li>
<li class="bar">Item #8</li>
</ul>
In short, anytime there’s 2 or more items with class=”foo”, they should be grouped together up until reaching a non-class=”foo” item. I can then use a link to show or hide the grouped items.
Here’s one possibility:
Example: http://jsbin.com/ipiki3/3/
EDIT: Fixed a mistake with the
lenvariable, and added an example.Explanation: What’s happening with the
.filter()is that it is narrowing theli.fooelements down to the first in a group (has at least oneli.fooafter it, and none before).Then with the
.each()it appends the<a>, get’s the next elements until it reaches one that is notli.foo, wraps those with a<ul>and returns how many there were using thelengthproperty.Then we traverse over to that new
<ul>and append it to the firstli.fooin the group.Finally we prepend the quantity we stored in the
lengthproperty to the<a>element.