Skip to content

Instantly share code, notes, and snippets.

@Gioni06
Last active September 10, 2019 14:53
Show Gist options
  • Save Gioni06/84205e3326c0d1ce554445f5fcbc7f44 to your computer and use it in GitHub Desktop.
Save Gioni06/84205e3326c0d1ce554445f5fcbc7f44 to your computer and use it in GitHub Desktop.
jQuery "closest" vs vanilla "closest"
<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>

jQuery "closest" vs vanilla "closest" vs native "closest"

Test jquery's closest() function against a vanilla js closest() function and the native closest() function

A Pen by Jonas D. on CodePen.

License.

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');
}
<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