Search code examples
jqueryselectordelegation

JQuery: Can I apply action on all selectors when using event delegation?


I have two UL's such as below

<ul id="ul_one">
    <li>list item</li>
    <li>list item</li>
    <li class="active">list item</li>
</ul>
<ul id="ul_two">
    <li>list item</li>
    <li>list item</li>
    <li class="active">list item</li>
</ul>

What I would like to do is first remove the 'active' class from <li>'s in BOTH <ul>'s and then apply the 'active' class to just the clicked item. For example

$('#ul_one, #ul_two').on('click', 'li', function(e)
{
    var clicked = e.target;
    $('#ul_one, #ul_two').find('li.active').removeClass('active');
    $(clicked).addClass('active');
});

Given the fact I am using delegation, is there a way I can remove the class from both <ul>'s without referencing them by name again. So instead of saying:

$('#ul_one, #ul_two').find('li.active').removeClass('active');

can I say something like:

$('ALL items in the original selector').find('li').removeClass('active');

Solution

  • Best thing is to cache the ULs.

    var uls = $('#ul_one, #ul_two');
    uls.on('click', 'li', function() {
        uls.find('li.active').removeClass('active');
        $(this).addClass('active');
    });