Elmar Babayev Elmar Babayev - 1 year ago 31
Javascript Question

Apply css-background for each element depending on parent's data attribute

I am making a rating bar with an element that has a data-rating attribute and it's children with 5 buttons. How can I change background-image of buttons depending on the data-rating attribute? For example if data-rating="3" - select first 3 buttons and change it's background.

This is my code:

var rating = $('#video-list .children .branch-opened .rating');
rating.each(function() {
var value = $(this).data('rating');
var button = $(this).find('button');
});


HTML:

<div class="rating" data-rating="4">
<button value="1"></button>
<button value="2"></button>
<button value="3"></button>
<button value="4"></button>
<button value="5"></button>
</div>


Many thanks!

Answer Source

This simple code will work for you.

var rating = $('.rating');
rating.each(function() {
  var rValue = $(this).data('rating'),
    bCount = $(this).find('button').slice(0, rValue).addClass('black');
});
.black {
  background-color: black;
}

.rating button {
  width: 10%;
  display: inline-block;
  padding: 20px;
  border: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="rating" data-rating="4">
  <button value="1"></button>
  <button value="2"></button>
  <button value="3"></button>
  <button value="4"></button>
  <button value="5"></button>
</div>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download