最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - jQuery element.closest(...).attr is not a function when using each - Stack Overflow

programmeradmin3浏览0评论

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

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

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 0
Add a comment  | 

4 Answers 4

Reset to default 5

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

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.

发布评论

评论列表(0)

  1. 暂无评论