Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery element.closest(...).attr is not a function when using each

When iterating over some DOM elements I found it impossible to use .data or .attr on them:

$('.running').each (index, element) =>
    console.log element.closest('[data-id]')

gets me

<section class="job-block" data-id="240"></section>
...

but

$('.running').each (index, element) =>
    console.log element.closest('[data-id]').data('id')

throws

Uncaught TypeError: element.closest(...).data is not a function

like image 992
The Whiz of Oz Avatar asked Jan 09 '17 10:01

The Whiz of Oz


Video Answer


2 Answers

The closest() method that you are using is native JS method and which returns DOM element object since element refers DOM element object.


There are several options to get the attribute value, either get from dataset property :
$('.running').each (index, element) =>
    console.log element.closest('[data-id]').dataset.id


Or wrap element by jQuery and use data() method.
$('.running').each (index, element) =>
    console.log $(element.closest('[data-id]')).data('id')


Or wrap the element by jQuery and use jQuery closest() method.
$('.running').each (index, element) =>
    console.log $(element).closest('[data-id]').data('id')
like image 55
Pranav C Balan Avatar answered Sep 18 '22 00:09

Pranav C Balan


Because they are DOM objects (as you rightly state) and not jquery objects, you can't apply jquery methods to DOM objects, you need to convert them to jquery objects.

$(element).closest...
like image 23
freedomn-m Avatar answered Sep 22 '22 00:09

freedomn-m