Which is more efficient: .parent().parent().parent() ~or~ parents(“.foo”) ~or~ closest(“.foo”)

前端 未结 7 1780
-上瘾入骨i
-上瘾入骨i 2020-12-15 03:06

I have an A tag which triggers the animation of it\'s great-great-great-grandparent. All of the following will work, but which is most efficient, and why?

$         


        
7条回答
  •  醉梦人生
    2020-12-15 03:59

    Well closest is only useful if you are going up or at the same level on the 'clicked' element.

    If for example you have to folowing scenario:

    Then closest('#otherone') will not find the hidden text field on $('.other-option').click() The better solution is in this scenario is to use $(this).parentsUntil('.radio-other').find('#otherone')

    Looking at my answer I made a jsperf here that reflects above scenario with different solutions. Just use what is the most usefull for your html scenario. the outcome is that parent().parent() is the fastest methode however this is not always a good option if your html is more flexible in use. Add a div parent and the parent().parent() breaks.

提交回复
热议问题