Reputation: 505
Code 1
jQuery("ul#leftmenuacc").find("span.leftmenutextspan")[0].css('color', 'red');
The above code doesn't work, so I had to do it another way [ below mentioned ]
Code 2
jQuery("ul#leftmenuacc").find('span.leftmenutextspan').each(function(index){ if(index ==0) jQuery(this).css('color', 'red') });
I am confused here as why didn't the Code 1
works? I read the documentation on .css
from Jquery Docs, but couldn't find what I am missing.
Is there an elegant way to do it? Because currently I am iterating through a lot of DOM Items for no use.
Upvotes: 4
Views: 116
Reputation: 11044
All of the other answers provide working solutions. If performance is not entirely unimportant to you, the following should be considered as well:
Refrain from using :eq
(or :first
, as suggested in some of the other answers) selectors whenever you can.
Usually, jQuery uses the browser's native querySelectorAll()
DOM traversal method, which is considerably faster than jQuery parsing the DOM tree on its own.
Since :eq
and :first
are jQuery-specific, querySelectorAll()
cannot be used – thus, jQuery has to resort to using its own, much slower, traversal engine instead.
The recommended alternative for this scenario is the use of jQuery's filter()
or first()
(which, afair, internally maps to filter()
) methods:
jQuery("ul#leftmenuacc").find("span.leftmenutextspan").first().css('color', 'red');
Quote jQuery's own documentation on :first
:
Because :first is a jQuery extension and not part of the CSS specification, queries using :first cannot take advantage of the performance boost provided by the native DOM querySelectorAll() method.
To achieve the best performance when using :first to select elements, first select the elements using a pure CSS selector, then use .filter(":first").
How much speed do you gain? Well, .first()
is around 10 times as fast as :first
in standard scenarios.
The use of find()
seems unnecessary in your example and slows your code for the same reason as mentioned above. This would be the better alternative:
jQuery("ul#leftmenuacc span.leftmenutextspan").first().css('color', 'red');
Upvotes: 0
Reputation: 11824
in Code 1 you are missing doublequotes (") after ul#leftmenuacc
and I'd do it like this
$("span.leftmenutextspan:first", "ul#leftmenuacc").css('color', 'red');
Upvotes: 0
Reputation: 22933
jQuery("ul#leftmenuacc").find("span.leftmenutextspan:first").css('color', 'red');
Upvotes: 0
Reputation: 16460
When you are doing $(selector)[0]
you will get HTMLElement, which hasn't got css
function. You may wrap it with jQuery like: $($(selector)[0])
, but better solution is to use :eq(0)
or :first
selector:
jQuery("ul#leftmenuacc").find("span.leftmenutextspan:eq(0)").css('color', 'red');
Upvotes: 3