Selector for best performance in jQuery?

后端 未结 3 1313
礼貌的吻别
礼貌的吻别 2020-12-20 22:16

I just spent 2 hours reading online guides and blogs about jQuery selectors. Everybody says different things and every last one of them seem to be so sure. I need an expert

3条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-20 22:20

    I did a benchmark test that show me it's better to choose more specific selectors.

    I tested this HTML :

    Awesome stuff!

    I like carrots!

    With 8 different selectors :

    $(' div#my-id div.grand div.parent div.my-class ').css("background-color", "#cccccc"); //case-1
    $(' #my-id .grand .parent div.my-class ').css("background-color", "#cccccc"); //case-2
    $(' #my-id .grand .parent .my-class ').css("background-color", "#cccccc"); //case-3
    $(' div#my-id div.my-class ').css("background-color", "#cccccc"); //case-4
    $(' #my-id div.my-class ').css("background-color", "#cccccc"); //case-5
    $(' #my-id .my-class ').css("background-color", "#cccccc"); //case-6
    $(' div.my-class ').css("background-color", "#cccccc"); //case-7
    $(' .my-class ').css("background-color", "#cccccc"); //case-8
    

    And results showed me that case-1, case-2 and case-3 are better than the others. you can see the result here.

提交回复
热议问题