lampropoi
lampropoi

Reputation: 131

Filtering an element using jQuery

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:

  1. How can I take the last element using jQuery?
  2. Is there anyway to use the filter function and if not why?
  3. Why I get undefined?

Upvotes: 4

Views: 80

Answers (2)

Tushar
Tushar

Reputation: 87203

  1. How can I take the last element using jQuery?

    You can use :last selector or last() method on the jQuery collection

  2. 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')
    
  3. Why I get undefined?

    $(this).closest('li').filter('.dutyText') will search for the closest ancestor <li> and will try to get the li having dummyText class from it. As the closest li don't have class dummyText, the selector will not select any element and so calling html() on empty object returns undefined.

Assuming there is only one element with class dummyText

  1. As the element is the sibling of the img, you can use siblings().

    $(this).siblings('.dutyText')
    
  2. You can also use parent-child hierarchy

    $(this).closest('li').find('.dutyText')
    

Multiple elements having dummyText class

  1. You can use :last selector to get the last element.

    $(this).closest('li').find('.dutyText:last')
    
  2. You can use last() method

    $(this).closest('li').find('.dutyText').last()
    

Upvotes: 5

Mushr00m
Mushr00m

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

Related Questions