Reputation: 131
I have the following li element:
<li>
<span><img src="../media/check.svg" class="complete"></span>
<span><img src="../media/modify.svg" class="modify"></span>
<span><img src="../media/delete.png" class="delete"></span>
<span class="dutyText">hello</span>
<li>
When an image is clicked (check.svg|modify.svg|delete.png), I want to get the last span element of the above list.
Unfortunately, with the following code, I get undefined:
console.log($(this).closest('li').filter('.dutyText').html());
The questions that I have are:
Upvotes: 4
Views: 80
Reputation: 87203
How can I take the last element using jQuery?
You can use
:last
selector orlast()
method on the jQuery collection
Is there anyway to use the filter function and if not why?
You can use
filter()
as follow. However, in this case, you don't need filter.
$(this).closest('li').children().filter('.dummyText')
Why I get undefined?
$(this).closest('li').filter('.dutyText')
will search for the closest ancestor<li>
and will try to get theli
havingdummyText
class from it. As the closestli
don't have classdummyText
, the selector will not select any element and so callinghtml()
on empty object returnsundefined
.
Assuming there is only one element with class dummyText
As the element is the sibling of the img
, you can use siblings()
.
$(this).siblings('.dutyText')
You can also use parent-child hierarchy
$(this).closest('li').find('.dutyText')
Multiple elements having dummyText
class
You can use :last
selector to get the last element.
$(this).closest('li').find('.dutyText:last')
You can use last()
method
$(this).closest('li').find('.dutyText').last()
Upvotes: 5
Reputation: 2356
1 : When you want the last element from a collection use .last()
.
2 : filter()
is meant to filter a collection of JQuery elements. In your case you want to select one depth deeper (children). So you need to do find()
.
3 : You get undefined because you're trying to get the HTML from an li
with the class .dutyText
. And it did not exists.
Upvotes: 1