Heliostatic
Heliostatic

Reputation: 175

Select the first element of a class 'x' after a link with jQuery

I've got some code like this:

<p>Lorem ipsum<a href=# class="a">link</a><span class="b">Text</span>More lorem ipsum<a href=# class="a">link</a><span class="b">Text 2</span>

And I'd like to let users click the link and be able to do something with the span (make it flash, hide it, whatever). I'm using jQuery, and this is what I've got so far:

$('.a').click(function() {
    $(this).nextUntil('.a').css('background-color', 'red');
 });

This works as long as I'm diligent about having links before the spans, and no other code in the text. However, I'm not happy with it, and there must be a better way. I've also tried:

$('.a').click(function() {
    $(this).next('.b').css('background-color', 'red');
 });

But that selects all of the spans of class b, so no good.

I'm new and at a loss. I seek wisdom.

Upvotes: 1

Views: 105

Answers (2)

rahul
rahul

Reputation: 187050

$('a.a').click(function() {
    $(this).next('span.b').css('background-color', 'red');
 });

should work fine for you. It gets the immediately following sibling.

Upvotes: 1

icktoofay
icktoofay

Reputation: 129001

Perhaps you could try this?

$(".a").click(function() {
    $(this).addClass("something_special");
    $(".something_special + .b").css({backgroundColor: "red"});
    $(this).removeClass("something_special");
});

Upvotes: 0

Related Questions