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
The closest()
method that you are using is native JS method and which returns DOM element object since element
refers DOM element object.
dataset
property :
$('.running').each (index, element) =>
console.log element.closest('[data-id]').dataset.id
data()
method.
$('.running').each (index, element) =>
console.log $(element.closest('[data-id]')).data('id')
element
by jQuery and use jQuery closest()
method.
$('.running').each (index, element) =>
console.log $(element).closest('[data-id]').data('id')
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...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With