6

What function can I use to select child div of class="rate_stars".

I have a variable range from 1 - 5 and I want to select child div with that specific data-rating.

I have tried

 $('rate_widget').find().attr('data-rating', info).prevAll().andSelf().addClass('ratings_vote');

But it did't work.

<div id="r1" class="rate_stars"
                             data-post-id="<?php echo $post_id ?>"
                             data-user-id="<?php echo $user_id;  ?>"
                             data-nonce="<?php echo $nonce ?>"
                            >
    <div data-rating="1" class="ratings_stars"></div>
    <div data-rating="2" class="ratings_stars"></div>
    <div data-rating="3" class="ratings_stars"></div>
    <div data-rating="4" class="ratings_stars"></div>
    <div data-rating="5" class="ratings_stars"></div>
    <div class="total_votes">vote data</div>
</div>
Siva.G ツ
  • 831
  • 1
  • 7
  • 20
Epistemologist
  • 1,052
  • 3
  • 15
  • 34

3 Answers3

11

You can use the attribute selector found in jQuery:

$('#r1').find('[data-rating="' + info + '"]')

Reference: List of All jQuery Attribute Selectors

War10ck
  • 12,387
  • 7
  • 41
  • 54
  • I am trying to add class to all its siblings but it doesn't work if i place the code in script.js but if i write it insdie console than it works perfectly. – Epistemologist Jul 23 '14 at 16:51
  • $('.rate_widget').find('[data-rating="' + INFO + '"]').prevAll().andSelf().addClass('ratings_vote'); – Epistemologist Jul 23 '14 at 16:52
  • @Epistemologist You probably want to open a new question for that issue. Are the elements added dynamically? If so, they may not be present when the script first runs. Also, `.andSelf()` is deprecated in 1.8. You should consider using the new function [`.addBack()`](http://api.jquery.com/addBack/) in it's place (requires jQuery 1.8+). – War10ck Jul 23 '14 at 17:50
  • 1
    This solution did not work for me. Then I tried `$('div[data-rating="1"'])` worked for me. Thanks. – Kamlesh Aug 07 '23 at 10:54
3

This should do the trick

var $div = $('.rate_stars div[data-rating="1"'])

Where 1 can be replaced by a dynamic expression if necessary

Claudio Redi
  • 67,454
  • 15
  • 130
  • 155
3

Another way from my experience is to do a jquery each over the elements then check the data attribute, e.g.

$( ".ratings_stars" ).each(function( index ) {
    if($(this).data('rating') == 1){
         //Do Something
    }
});
joegandy
  • 320
  • 1
  • 5
  • This works but will add an excessive amount of overhead for this small of task. Also note that the class is `ratings_stars` (plural on _ratings_)... – War10ck Jul 23 '14 at 15:52
  • 1
    Very true, I've learnt more from the other answers. Thanks for the heads up on the typo – joegandy Jul 23 '14 at 15:55