How to traverse the siblings with jQuery?

1

What I want to do is that when I hover over a star, all previous ones have a "selected" class, I tried to use siblings together with each one and I almost got the result where I wanted it.

The result I want to get is something like this: JQUERY

$('.estrela').on({'mouseenter':function(){$(this).siblings().each(function(){$(this).removeClass("fa-star-o").addClass("fa-star");
        });
    }, 'mouseleave': function () {
        $(this).removeClass("fa-star").addClass("fa-star-o");
    }
});

HTML

<form>
    <h5>1 - Quantas estrelas você recomenda?</h5>
    <?php for ($i = 1; $i <= 5; $i++): ?>
     <a href="#" class="estrela fa fa-star-o" data-estrelas="<?= $i; ?>"></a>
    <?php endfor; ?>
 </form>
    
asked by anonymous 28.05.2017 / 18:32

1 answer

1

Use event.target to know the current element, and iterates the collection every time. Then with a return false; you make the loop stop.

Suggestion:

var estrelas = $('.estrela');
estrelas.on({
  'mouseenter': function(e) {
    estrelas.each(function() {
      $(this).removeClass("fa-star-o").addClass("fa-star");
      if (this === e.target) return false;
    });
  },
  'mouseleave': function(e) {
    $(this).removeClass("fa-star").addClass("fa-star-o");
  }
});
a {
  text-decoration: none;
  color: #ECC202;
}
<link href="https://netdna.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><ahref="#" class="estrela fa fa-star-o"></a>
<a href="#" class="estrela fa fa-star-o"></a>
<a href="#" class="estrela fa fa-star-o"></a>
<a href="#" class="estrela fa fa-star-o"></a>
<a href="#" class="estrela fa fa-star-o"></a>
    
28.05.2017 / 18:55