JQuery: grouping related items

Using jQuery, I am trying to group similar items in a list. Here is what I am trying to do. Given a list as below:

<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 would like to get 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, at any time when there are 2 or more elements with class = "foo", they should be grouped together until the class = "foo" element is reached. Then I can use the link to show or hide grouped items.

+3
source share
2 answers

Here is one possibility:

Example: http://jsbin.com/ipiki3/3/

$('ul > li.foo')
    .filter(function() {
        var $th = $(this);
        return $th.next('li.foo').length && !$th.prev('li.foo').length;
    })
    .each(function() {
        var $th = $(this);
        var len= $th.append('<a href="#"> more like this</a>')
                    .nextUntil(':not(li.foo)').wrapAll('<ul>').length;
        $th.next('ul').appendTo(this);
        $th.children('a').prepend(len);
    });

EDIT: Fixed a bug with a variable lenand added an example.


: .filter(), , li.foo ( li.foo )).

.each() <a>, , , li.foo, , <ul>, length.

<ul> li.foo .

, , length, <a>.

+3

:

$(document).ready(function() {
    var groups = {}
    $('ul li').each(function() {
        var self = $(this);
        var class_name = self.attr('class');
        if (class_name) {
            if (typeof groups[class_name] == 'undefined') {
                groups[class_name] = [];
            }
            groups[class_name].push(self);
        }
    });
    var ul = $('ul');
    ul.empty();
    for (var class_name in groups) {
        var array = groups[class_name];
        ul.append('<li class="' + class_name + '">' + $(array[0]).html() + 
            '<a>More Like this</a><ul></ul>');
        $(array.splice(1)).each(function() {
            ul.find('li.' + class_name + ' ul').append(this);
        });
    }
});
+2

Source: https://habr.com/ru/post/1767763/


All Articles