最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - improve inefficient jQuery selector - Stack Overflow

programmeradmin1浏览0评论

In IntelliJ, if I use a jQuery selector such as:

$('#roleField option').each(function() {
    // impl omitted
});

The selector is highlighted with a suggestion that I should

split descendant selectors which are prefaced with ID selector

what exactly is IntelliJ suggesting that I should replace the selector above with?

In IntelliJ, if I use a jQuery selector such as:

$('#roleField option').each(function() {
    // impl omitted
});

The selector is highlighted with a suggestion that I should

split descendant selectors which are prefaced with ID selector

what exactly is IntelliJ suggesting that I should replace the selector above with?

Share Improve this question asked May 7, 2014 at 12:38 DónalDónal 187k177 gold badges584 silver badges843 bronze badges 10
  • 4 I think $('#roleField').find('option') – Arun P Johny Commented May 7, 2014 at 12:39
  • Not sure if it's what it's referring to or not, but using find for child selectors has been proven to be considerably faster - $('#roleField').find('option').each() – Reinstate Monica Cellio Commented May 7, 2014 at 12:39
  • 1 possible duplicate of Inefficient jQuery usage warnings in PHPStorm IDE – Reinstate Monica Cellio Commented May 7, 2014 at 12:43
  • 1 Seems like a silly warning. While using .find might improve speed by a couple milliseconds, it's not really worth the sacrifice in easy readability. I personally (have been using jQuery PROFESSIONALLY for 6 years now) don't use .find unless it's on an assigned variable. If I have a selector, like you show above, I just do exactly what you're doing, $('#id child'). There's really no reason to replace it with $('#id').find('child') – SpYk3HH Commented May 7, 2014 at 12:46
  • 1 I think because if you use id selector alone then jQuery might use getElementById() to fetch first record... – Arun P Johny Commented May 7, 2014 at 12:46
 |  Show 5 more comments

2 Answers 2

Reset to default 19

From the jquery documentation this method will not go through the Sizzle sector engine:

$('#roleField option').each(function() {
    // No Sizzle
}); 

Where this one will:

$('#roleField').find('option')  // Sizzle!

Look at the ID base selectors section here. Hence the second method will be faster than the first.

Try to use .find() here:

$('#roleField').find('option').each(function() {
    // impl omitted
});

Your warning seem like related to efficiency of the selector.

Related thread

发布评论

评论列表(0)

  1. 暂无评论