最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Parallel element selector - Stack Overflow

programmeradmin2浏览0评论

We have the following situation:

<ul>
    <li>Button 1</li>
    <li class="active">Button 2</li>
    <li>Button 3</li>
    <li>Button 4</li>
</ul>

now the following code that handles it:

    $('.tab-menu li').on('click', function() {
        $($($(this).closest('.tab-menu')).find('li')).removeClass('active');
        $(this).addClass('active');
    });

it works, but is there a jQuery function that selects all 'parallel' elements ? I want this part

$($($(this).closest('.tab-menu')).find('li')).removeClass('active');

make shorter. I know 'toggleClass', but this works only on the clicked element. Is there any shorter method to select all parallel elements? (In this siutation all 'li' that belongs to the specific 'ul');

We have the following situation:

<ul>
    <li>Button 1</li>
    <li class="active">Button 2</li>
    <li>Button 3</li>
    <li>Button 4</li>
</ul>

now the following code that handles it:

    $('.tab-menu li').on('click', function() {
        $($($(this).closest('.tab-menu')).find('li')).removeClass('active');
        $(this).addClass('active');
    });

it works, but is there a jQuery function that selects all 'parallel' elements ? I want this part

$($($(this).closest('.tab-menu')).find('li')).removeClass('active');

make shorter. I know 'toggleClass', but this works only on the clicked element. Is there any shorter method to select all parallel elements? (In this siutation all 'li' that belongs to the specific 'ul');

Share Improve this question edited Sep 9, 2013 at 13:07 Oskar Szura asked Sep 9, 2013 at 12:57 Oskar SzuraOskar Szura 2,5695 gold badges34 silver badges43 bronze badges 10
  • 1 Isn't that entire first part redundant? $($(this).closest('.tab-menu')).find('li')) is already this – tymeJV Commented Sep 9, 2013 at 12:59
  • 1 no it will be a list of all the li's under .tab-menu not just the one currently being iterated over – DGS Commented Sep 9, 2013 at 13:00
  • @DGS But he iterates over all of them. It's nonsensical code. – Reinstate Monica Cellio Commented Sep 9, 2013 at 13:01
  • 1 You don't need to keep recasting things to jquery objects (the $($($(). Nearly all jquery functions return jquery objects. The only one that I know of which does not is get which is explicitly for getting the dom element out of the jquery object. – MushinNoShin Commented Sep 9, 2013 at 13:01
  • 1 @OskarSzura Should the code above really say each?? – Reinstate Monica Cellio Commented Sep 9, 2013 at 13:04
 |  Show 5 more ments

1 Answer 1

Reset to default 8

Try this, using .siblings()

$(this).addClass('active').siblings().removeClass('active');

DEMO with onclick

发布评论

评论列表(0)

  1. 暂无评论