Performance of jQuery Selectors with ID

后端 未结 9 2029
有刺的猬
有刺的猬 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.

提交回复
热议问题