Tom
Tom

Reputation: 12998

Using :not selector with $(this)

I have the following line which works OK

$("#myDiv img:not(:eq(0))").hide();

I want to write a similar line but using "this". So:

$(this":not(:eq(0))").hide();

But that doesn't work... Any ideas where it's gone wrong?

Upvotes: 3

Views: 387

Answers (5)

David Tang
David Tang

Reputation: 93694

The other answers are forgetting an important point - this is most likely in some event callback, and is likely a single element, so it is always the first element in the selection (:eq(0)).

Therefore each the following equivalent snippets will never hide anything:

$(this).not(':eq(0)').hide();
$(this).filter(':gt(0)').hide();
$(this).slice(1).hide();

I am only guessing the OP's intent here, but the code should most likely be:

if ($(this).index('#myDiv img') > 0) $(this).hide();

Upvotes: 5

hunter
hunter

Reputation: 63542

It seems like you should be using the :gt() selector

Description: Select all elements at an index greater than index within the matched set.

try:

$(this).find(":gt(0)").hide();

or:

$(":gt(0)", this).hide();

isn't :not(:eq(0)) a clunky way of writing :gt(0)?

Upvotes: 2

Joseph
Joseph

Reputation: 25523

Something like this should work:

$(this).not(":eq(0)").hide();

Upvotes: 3

Ivan Ivanic
Ivan Ivanic

Reputation: 3054

$($(this).selector + ":not(:eq(0))").hide();

Upvotes: 0

chris
chris

Reputation: 505

try .not(selector) http://api.jquery.com/not/

Upvotes: 6

Related Questions