jonathanbell
jonathanbell

Reputation: 2637

Select the next matching class/element when not immediately placed after original selector in jQuery

I think I've almost got it, but not there quite...

I want to select the a.rate-button out of this HTML only when an element one level up and two levels down in the DOM contains a certain string. I know that this is stretching the limits of a jQuery selector but it's just for fun and not production.

HTML:

<div class="comment">

    <div class="submitted">
        <a href="#" title="View user profile.">Blow, Jo</a>  
    </div><!-- CLASS submitted -->

    <div class="content">
        <p>blah</p>
        <p>blah</p>
        <p>blah</p>
  </div><!-- CLASS content -->

      <ul class="links">
        <li class="comment_delete first"><a href="/comment/delete/1204">delete</a></li>
            <li class="comment_edit"><a href="/comment/edit/1204">edit</a></li>
            <li class="flag_content_add">hippo</li>
            <li class="rate_thumbup_comments last">
                <span>
                    <div class="rate-widget-1 rate-widget clear-block rate-average">
                        <a class="rate-button" rel="nofollow" href="#">up</a>
                        <div class="rate-info">1 person likes this.</div>
                    </div>
                </span>
            </li>
        </ul>

</div>

The jQuery selector I've got thus far:

$('.submitted a:contains("Blow")').parent().parent().next('.links .rate_thumbup_comments .rate-widget').find('a').css('display', 'none');

So, to reiterate: I want to select the tag inside div.rate-widget which is inside li.rate_thumbup_comments only when container div.submitted has an with a string inside it of "Blow". All of this is within the container div.comment

Upvotes: 0

Views: 175

Answers (2)

tonyellard
tonyellard

Reputation: 156

This seems to work with the html you provided:

$('.submitted a:contains("Blow")').parent().parent().children('.links').find('.rate-button').css('display', 'none');

Upvotes: 1

Kevin B
Kevin B

Reputation: 95020

So, for example, you want to hide all rating widgets for comments for a specific user. Correct me if i'm wrong.

$('.submitted a:contains("Blow")').closest(".comment").find('.rate-widget a').hide();

Is that what you are essentially trying to do?

.next() only selects the very next element, and only if it matches the selector if one is passed in. If you need to select an element that isn't immediately next, use .nextUntil(targetselector).next(), or in you case, .nextUntil(".links").next()

Upvotes: 1

Related Questions