Performance of jQuery Selectors with ID

后端 未结 9 2016
有刺的猬
有刺的猬 2021-01-12 10:52

I know in jQuery if we use ID to select elements,it\'s so efficient.I have a question about this selectors:

please consider this 3 selectors:

         


        
相关标签:
9条回答
  • 2021-01-12 11:49

    Obviously the first one, $("#MyElement") is faster than other 2.
    Accessing an element with its id always faster but sometimes we had to find some element in some container. In that case we prefer .find() or .filter() (depending upon situation).
    The difference between selectors depends on browser to browser. e.g. if you access through class on IE it would be slower than FF. FF is faster when accessing an element with class rather than ID.

    In your second example, i.e. $("#mytbl #MyElement"), here you are finding #MyElement under #mytbl which is legal but not appropriate way. Since you already know the ID of the element (assuming you have only one element with this id on your page) so its better to use $("#MyElement"). $("#mytbl #MyElement") will read #mytbl first and traverse to find #MyElement under it hence time consuming and slow.

    To test different cases you can write small snippet to read/access atleast 10000 elements in a loop otherwise it would be hard to determine which way is faster.

    0 讨论(0)
  • 2021-01-12 11:50

    Also, if you need nested selectors, it's faster to use $().find().find()

    http://jsperf.com/selector-test-id-id-id-id-class/2

    $('#Mytbl .MyClass')
    $('#Mytbl').find('.MyClass')
    

    The latter is about 65% faster.

    0 讨论(0)
  • 2021-01-12 11:58

    A direct ID selector will always be the fastest.

    I've created a simple test case based on your question...

    http://jsperf.com/selector-test-id-id-id-id-class

    Selecting nested ID's is just wrong, because if an ID is unique (which it should be), then it doesn't matter if it's nested or not.

    0 讨论(0)
提交回复
热议问题