Jquery element+class selector performance

后端 未结 4 944
萌比男神i
萌比男神i 2020-12-12 18:09

I was hoping $(\'#childDiv2 .txtClass\') or $(\'#childDiv2 input.txtClass\') perform better when selecting

4条回答
  •  误落风尘
    2020-12-12 18:46

    Modern browsers expose a very efficient getElementsByClassName() method that returns the elements having a given class. That's why a single class selector is faster in your case.

    To elaborate on your examples:

    $(".txtClass")                  =>  getElementsByClassName()
    
    $("#childDiv2 .txtClass")       =>  getElementById(),
                                        then getElementsByClassName()
    
    $("#childDiv2 > .txtClass")     =>  getElementById(),
                                        then iterate over children and check class
    
    $("input.txtClass")             =>  getElementsByTagName(),
                                        then iterate over results and check class
    
    $("#childDiv2 input.txtClass")  =>  getElementById(),
                                        then getElementsByTagName(),
                                        then iterate over results and check class
    

    As you can see, it's quite logical for the first form to be the fastest on modern browsers.

提交回复
热议问题