jqueryeachtoggleclass

Jquery each toggleClass


So, i'm using a foreach that generates "li's" in a menu. Currently there are only two "li's". This menu becomes thiner when you click on a button and i wanted to decrease the font-size when this happens.

I've tried using the toggleClass() function inside an each() function to do this but only the first "li" toggles the class, the second remais the same.

foreach ($results as $result){
                       $local = $result['local'];
                   echo "<li><a class='clsPostData1' data-local='".$result['local']."' data-salaid='".$result['salaid']."' data-salakey='".$result['salakey']."'href='#'><span id='idfontsala'>".$local."</span></a></li>";
                   }

I'm using the "idfontsala" ID inside a span.

<script>

      $(document).ready(function(){
  $('.sidebar-toggle').click(function(){
    $('#idfontsala').each(function(){
      $(this).toggleClass('classfontsala');
    });
  });
});

  </script>

This is what is happening : https://i.imgsafe.org/34d4f934b5.png


Solution

  • If you want all generated items to be affected. Use a class to match multiple elements. Replace your markup with:

     <span class='fontsala'>
    

    And your script with:

     $('.fontsala').each(function(){
      $(this).toggleClass('classfontsala');
    });
    

    UPDATE:

    This is if you still want to use $.each. But as @Barmar said, it can be shortened.

    $('.fontsala').toggleClass('classfontsala');