10

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?

10
  • 4
    I think $('#roleField').find('option') 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() Commented May 7, 2014 at 12:39
  • 1
    possible duplicate of Inefficient jQuery usage warnings in PHPStorm IDE 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... Commented May 7, 2014 at 12:46

2 Answers 2

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.

5

Try to use .find() here:

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

Your warning seem like related to efficiency of the selector.

Related thread

4
  • Already answered in the comments and the link you posted. You shouldn't post links as answers - you should use the close button. Commented May 7, 2014 at 12:45
  • @Archer yes, but he's providing an actual answer. Although, before you go telling people it's "considerably" faster, please post some proof. I've been using child selectors and saving .find for use only on variables for years and never seen any "considerable" difference. In other words, I've never considered it to be much faster and I've tried it both ways in the my early days.
    – SpYk3HH
    Commented May 7, 2014 at 12:48
  • 3
    @Archer Comments are comments, answers are answers and this is IntelliJ and not PHPStorm and I'm not posting link as an anser as well.
    – Felix
    Commented May 7, 2014 at 12:49
  • The link you provided shows the exact same issue with the exact same code change that you have suggested. You should have pointed this out to the OP with the link. Commented May 7, 2014 at 13:11

Not the answer you're looking for? Browse other questions tagged or ask your own question.