95

Can you help me with this jQuery selector?

$(".auctiondiv .auctiondivleftcontainer .countdown").each(function () {
    var newValue = parseInt($(this).text(), 10) - 1;
    $(this).text(newValue);

    if (newValue == 0) {
        $(this).parent().fadeOut();
        chat.verify($(this).parent().parent().attr('id'));
    }
});

Basically, I want to select the element with .bidbutton class that belongs in the same parent as the .countdown in the each loop:

<div class="auctiondivleftcontainer">
    <p class="countdown">0</p>
    <button class="btn primary bidbutton">Lance</button>                            
</div>  

And then apply this to that button:

$(button here).addClass("disabled");
$(button here).attr("disabled", "");
Tchami
  • 4,647
  • 1
  • 32
  • 45
Only Bolivian Here
  • 35,719
  • 63
  • 161
  • 257

10 Answers10

166

Use jQuery .siblings() to select the matching sibling.

$(this).siblings('.bidbutton');
Madara's Ghost
  • 172,118
  • 50
  • 264
  • 308
7
$(this).siblings(".bidbutton")
JohnD
  • 3,884
  • 1
  • 28
  • 40
6
$("h2").siblings().css({"color": "blue"});
Samuel Liew
  • 76,741
  • 107
  • 159
  • 260
Sourav Basak
  • 486
  • 1
  • 4
  • 15
4
$("selector").nextAll(); 
$("selector").prev(); 

you can also find an element using Jquery selector

$("h2").siblings('table').find('tr'); 
Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219
Barath Kumar
  • 439
  • 3
  • 7
4
you can use 
$(this).siblings(".bidbutton").addClass("disabled");
$(this).siblings(".bidbutton").attr("disabled","");
Sarasjd
  • 199
  • 2
  • 11
1

If you want to select a specific sibling:

var $sibling = $(this).siblings('.bidbutton')[index];

where 'index' is the index of the specific sibling within the parent container.

Peter Meadley
  • 509
  • 2
  • 16
0

also if you need to select a sibling with a name rather than the class, you could use the following

var $sibling = $(this).siblings('input[name=bidbutton]');
Shobi
  • 10,374
  • 6
  • 46
  • 82
0

If I understood that correctly you're already in a loop (each) so you would always want to select that one sibling button inside each loop runthrough? Since siblings() returns an array, this would be the way to go:

$(this).siblings('.bidbutton')[0]

You can apply both things you wanted in a single line doing this:

$(this).siblings('.bidbutton')[0].addClass("disabled").attr("disabled", "");
Tarik A.
  • 3
  • 2
0

Since $(this) refers to .countdown you can use $(this).next() or $(this).next('button') more specifically.

AlienWebguy
  • 76,997
  • 17
  • 122
  • 145
0

Try -

   $(this).siblings(".bidbutton").addClass("disabled").attr("disabled", "");
ipr101
  • 24,096
  • 8
  • 59
  • 61