0

I want to remove all options but the first from my <select/>. I understand that children() would not work recursively.

Is there any difference between

$('#mySelect :gt(0)').remove();

and

$('#mySelect').find(':gt(0)').remove();

?

3
  • 1
    in second method you can use end() , to get #mySelect Commented Oct 10, 2015 at 13:44
  • 1
    In first method same can be done using closest
    – Tushar
    Commented Oct 10, 2015 at 13:46
  • Funny sidenote: I switched to phpStorm today. It told me to change it to .(find) so it's more efficient. stackoverflow.com/questions/12674591/…
    – phil294
    Commented Oct 11, 2015 at 15:45

2 Answers 2

3

Shockingly I can't find a duplicate of this question, all the others are about speed.

There's no significant difference in the two lines of code you've quoted, no.

3
  • 1
    That's it, you can add the comments(from Pranav) text in answer, that's helpful
    – Tushar
    Commented Oct 10, 2015 at 13:51
  • 1
    ikr!! that's kinda the reason for me asking that, honestly. :p
    – phil294
    Commented Oct 10, 2015 at 13:52
  • Check this 24ways.org/2011/your-jquery-now-with-less-suck please read the first section Selector speed: fast or slow?
    – Tushar
    Commented Oct 14, 2015 at 4:59
1

find() method is useful if we already have parent element reference:

 var parentElement = $('#mySelect');
    /*
    * there is some code..
    * do some thing on parent
    */

Now if we want to get parentElement's children we can use either

parentElement.find('.xtz'); or $('.xtz',parentElement)

rather than using complete selector either

$('#mySelect .xtz'); or $('#mySelect').find('.xtz');

1
  • Context selector can also be used in this case, $('.xyz', parentElement);
    – Tushar
    Commented Oct 10, 2015 at 14:31

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