0

Hi,

What's difference between:

  $('li:first').css('background-color', 'red');

And

  $('li').first().css('background-color', 'red');

Thanks!

3 Answers 3

5

They will both perform the same action.

The second one will gather all <li> tags into a jQuery object, then retrieve the first one in a separate jQuery object.
If you have many <li> tags, that may be slow.

On the other hand, the first one will not be able to use querySelectorAll() (since there is no :first CSS selector), so it may be slower too.

Sign up to request clarification or add additional context in comments.

Comments

1

The main difference is what is being brought back in the first call to operate on.

$('li:first') Will either bring back the first item or nothing (if none are found).

$('li').first() Will bring back all <li> items and then select the first item in the list for you to continue operating on.

Performance wise they likely both have the same impact so it's a matter of preference and style.

Comments

1

li:first is like direct selector by jquery li.first(). - you are selecting child elements using jquery method.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.