Iladarsda
Iladarsda

Reputation: 10694

jQuery shorthand

Is there any more elegant way to write that? :

var AllOperation = $('#menu > li.operation');
var Operation1= AllOperation[0];
$(Operation1).addClass('operation-first');

Upvotes: 1

Views: 115

Answers (3)

Gabriele Petrioli
Gabriele Petrioli

Reputation: 196207

If you want to target a specific element in a jQuery object you can use the .eq() method

For the first one you should use 0 (the method is 0 based)

$('#menu > li.operation').eq(0).addClass('operation-first');

If you only want to target the first, you can use the :first selector or .first() method (as mentioned in the other answers)

Upvotes: 2

Tatu Ulmanen
Tatu Ulmanen

Reputation: 124828

$('#menu > li.operation').first().addClass('operation-first')

Or

$('#menu > li.operation:first').addClass('operation-first')

Upvotes: 5

sushil bharwani
sushil bharwani

Reputation: 30197

$('#menu > li.operation:first').addClass('operation-first');

Upvotes: 1

Related Questions