Sheehan Alam
Sheehan Alam

Reputation: 60879

How can I break out of an each() in jQuery?

I have the following HTML + JS. I want the toggleButton to only toggle the first io-section-header. Eventually I will have multiple toggleButton's that will toggle a unique ul.

How can I achieve this?

<!DOCTYPE html>
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
  <div><span>Section 1</span></div>
  <div class="io-section-header">
  <ul>
    <li class="advanced">Accounts</li>
    <li class="advanced">People</li>
    <li class="advanced">companies</li>
    <li class="basic">She</li>
  </ul>
   <div><span>Section 2</span></div>
   <div class="io-section-header">
    <ul>
    <li class="advanced">Accounts</li>
    <li class="advanced">People</li>
    <li class="advanced">companies</li>
    <li class="basic">P</li>
  </ul>
  </div>
  </div>

  <div class="toggleButton">Collapse</div>

<script>
    jQuery(function ($) {
        $('.toggleButton').click(function () {  
            var currentText = $(this).text();
            if(currentText === "Collapse")
                $(this).text("Expand");
            else
                $(this).text("Collapse");

            /*$('.io-section-header').each(function() {
                $("li").siblings(".advanced").toggle('fast',function(){});
            });*/

            $('.io-section-header li').siblings(".advanced").toggle('fast'); 

        });
    });
</script>

</body>
</html>

Upvotes: 1

Views: 216

Answers (3)

Alon Eitan
Alon Eitan

Reputation: 12025

This will toggle the first advanced class in each io-section-header class

$('ul li.advanced:first', '.io-section-header').toggle('fast',function(){});

This will toggle the first advanced class in the first io-section-header class

$('ul li.advanced:first', '.io-section-header:first').toggle('fast',function(){});

Upvotes: 1

millimoose
millimoose

Reputation: 39950

From the .each() documentation:

We can break the $.each() loop at a particular iteration by making the callback function return false. Returning non-false is the same as a continue statement in a for loop; it will skip immediately to the next iteration.

Upvotes: 4

zzzzBov
zzzzBov

Reputation: 179046

return false is all you need; why aren't you using first()?

Upvotes: 0

Related Questions