Hi,
What's difference between:
$('li:first').css('background-color', 'red');
And
$('li').first().css('background-color', 'red');
Thanks!
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.
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.