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
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
Share Improve this question edited Jan 9, 2017 at 10:09 Zakaria Acharki 67.5k15 gold badges78 silver badges105 bronze badges asked Jan 9, 2017 at 10:05 The Whiz of OzThe Whiz of Oz 7,0439 gold badges52 silver badges91 bronze badges 0Uncaught TypeError: element.closest(...).data is not a function
4 Answers
Reset to default 5The 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')
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...
The element
contains a DOMElement, so you're calling the native closest() method, not the jQuery one. Hence the data()
method does not exist on the returned object.
To fix this, wrap element
in a jQuery object:
$('.running').each (index, element) =>
console.log $(element).closest('[data-id]').data('id')
data()
is a jQuery method so you should call it on jQuery object instead of a DOM oject, so it should be $(element)
:
console.log $(element).closest('[data-id]').data('id')
Hope this helps.