开发者

Using .css property in jQuery

开发者 https://www.devze.com 2023-04-12 16:24 出处:网络
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 wa开发者_JAVA百科y [ below mentioned ]

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 wa开发者_JAVA百科y [ 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.


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');


jQuery("ul#leftmenuacc").find("span.leftmenutextspan:first").css('color', 'red');


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');


All of the other answers provide working solutions. If performance is not entirely unimportant to you, the following should be considered as well:

  1. 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.

  2. 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');
    
0

精彩评论

暂无评论...
验证码 换一张
取 消