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>
1

3 Answers 3

11

You can use the attribute selector found in jQuery:

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

Reference: List of All jQuery Attribute Selectors

Sign up to request clarification or add additional context in comments.

4 Comments

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.
$('.rate_widget').find('[data-rating="' + INFO + '"]').prevAll().andSelf().addClass('ratings_vote');
@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() in it's place (requires jQuery 1.8+).
This solution did not work for me. Then I tried $('div[data-rating="1"']) worked for me. Thanks.
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

Comments

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
    }
});

2 Comments

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)...
Very true, I've learnt more from the other answers. Thanks for the heads up on the typo

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.