M Usama Alvi
M Usama Alvi

Reputation: 207

.addClass not working on individual Spans

$(event.currentTarget).closest('.segment').find('span').addClass('hide')

I have written this line on click function and it works fine. The issue is that it works on all the three spans that it returns. I want only the second span to add class of HIDE. If i try the below code it says the .addClass() is not a function.

$(event.currentTarget).closest('.segment').find('span')[0].addClass('hide')

Upvotes: 0

Views: 441

Answers (3)

user10038293
user10038293

Reputation:

Have you tried eq? Maybe something like this:

$(event.currentTarget).closest('.segment').find('span:eq(1)').addClass('hide');

Upvotes: 0

Manoj
Manoj

Reputation: 1195

if you need to target span at specific index you can also use :nth-child selector.

$(event.currentTarget).closest('.segment').find('span:nth-child(2)').addClass('hide')

Upvotes: 1

Satpal
Satpal

Reputation: 133403

Use .eq(index) method / :eq(index) selector instead of [0].

Since [0] returns the reference of DOM element which doesn't have the method thus it throws the error.

$(event.currentTarget).closest('.segment').find('span').eq(0).addClass('hide')
$(event.currentTarget).closest('.segment').find('span:eq(0)').addClass('hide')

Upvotes: 6

Related Questions