bob_cobb
bob_cobb

Reputation: 2269

Selecting previous anchor tag and adding a class to it with jQuery

Basically I've got two anchor tags separated by a div.

<a class="foo"></a>

<div class="count">0</a>

<a class="bar"></a>

and I'm doing something like this:

       var addClass = $(this).parent().children('a:first-child').addClass('new');

It will then add it to the first anchor tag like so:

<a class="foo new"></a>

I know using the nth:child selector is pretty expensive, so I was wondering if there was an easier way to select that previous anchor node, (while ignoring the second one).

Upvotes: 1

Views: 3205

Answers (3)

T.J. Crowder
T.J. Crowder

Reputation: 1074495

I'd probably combine prevAll with first (or eq(0), since first just calls eq(0) — but I find first more readable):

$(this).prevAll("a").first().addClass("new");
// or
$(this).prevAll("a").eq(0).addClass("new");

prevAll returns all of the element's preceding siblings, in order starting with the closest sibling, and of course first / eq(0) reduces the set to the first element.

You might be tempted to use the :first selector with prevAll to avoid building up an unnecessary list of siblings, but to my surprise it works better to use first after-the-fact.

Upvotes: 2

N3dst4
N3dst4

Reputation: 6435

How about:

$(this).siblings('a').eq(0).addClass(0);

Actually, if your structure is as simple as in your example, you can just do a simple:

$(this).prev().addClass(0);

jQuery's traversal methods give you lots of ways to get to any given destination.

Upvotes: 0

maček
maček

Reputation: 77778

You could do this

$(this).parent().children('a:eq(0)').addClass('new');

Learn more about :eq()

Alternatively, if there are no elements between the <a> and the <div>, you could do

$(this).prev('a');

Learn more about .prev()

Upvotes: 3

Related Questions