Test jquery's closest() function against a vanilla js closest() function and the native closest() function
Last active
September 10, 2019 14:53
-
-
Save Gioni06/84205e3326c0d1ce554445f5fcbc7f44 to your computer and use it in GitHub Desktop.
jQuery "closest" vs vanilla "closest"
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<nav id="test"> | |
<li><a href="/1">1</a></li> | |
<li><a href="/2">2</a></li> | |
<li><a href="/3" id="qs1">3</a></li> | |
<li><a href="/4">4</a></li> | |
</nav> | |
<nav id="test2"> | |
<li><a href="/1">1</a></li> | |
<li><a href="/2">2</a></li> | |
<li><a href="/3" id="qs2">3</a></li> | |
<li><a href="/4">4</a></li> | |
</nav> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function closest(el, fn) { | |
return el && (fn(el) ? el : closest(el.parentNode, fn)); | |
} | |
const jqueryClosest1 = $('#qs1').closest('nav'); | |
const vanillaClosest1 = closest(document.querySelector('#qs1'), e => e.matches('nav')) | |
const nativeClosest1 = document.querySelector('#qs1').closest('nav') | |
const jqueryClosest2 = $('#qs2').closest('nav'); | |
const vanillaClosest2 = closest(document.querySelector('#qs2'), e => e.matches('nav')) | |
const nativeClosest2 = document.querySelector('#qs2').closest('nav') | |
// @test jquery closest and vanilla closest should result in the same element | |
if(vanillaClosest1.isSameNode(jqueryClosest1[0]) && vanillaClosest1.isSameNode(nativeClosest1)) { | |
console.log('Nodes are equal'); | |
} else { | |
console.error('Nodes are not equal'); | |
} | |
if(vanillaClosest2.isSameNode(jqueryClosest2[0]) && vanillaClosest2.isSameNode(nativeClosest2)) { | |
console.log('Nodes are equal'); | |
} else { | |
console.error('Nodes are not equal'); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment