JQuery.closest () method returns undefined on iOS devices

JQuery . closeest () doesn't work on iOS devices. I use .closest()

c event.target

to determine if the affected target has a specific ancestor. Unfortunately this is returning and a bug on iOS devices.


Html

<ul class="level-1">
    <li><a href="#" class="item-1">Level 1 - Item 1</a></li>
    <li><a href="#" class="item-2">Level 1 - Item 2</a></li>
    <li><a href="#" class="item-3">Level 1 - Item 3</a></li>
</ul>

      

JQuery

$('.item-1').on('touchstart', function(e) {
    e.preventDefault();
    console.log(e.target.closest('.level-1'));
});

      

Mistake

enter image description here


A Live example can be found at the jsfiddle .

+3


source to share


2 answers


You are calling the dom element closest method ( e.target

is a reference to the dom element) which is an experimental feature (only a few browsers supported ), need to call jQuery closest () method for browser compatibility



console.log($(e.target).closest('.level-1'));

      

+3


source


You can also use "$ (this)" to find the closest element. It basically returns a jquery object to call the nearest jquery function



$('.item-1').on('touchstart', function(e) {
  e.preventDefault();
  console.log($(this).closest('.level-1'));
});

      

0


source







All Articles