tags:

views:

100

answers:

3

Hi All

Having a hard time to grab a title from a list, here is my code.

  <ul class="selected connected-list ui-sortable" style="height: 170px;">
    <li class="ui-helper-hidden-accessible" style=""/>
    <li class="ui-state-default ui-element" title="80 Days" style="display: list-item;"><span class="ui-icon ui-icon-arrowthick-2-n-s"/>80 Days<a class="action" href="#"></a>
    </li>
  </ul>

The first list item will not have a tile so it will always be the second list item.

$("ul.selected").closest("li").attr("title");

But getting no result. Hope you can advise !!

Thank you in advance if you can

+3  A: 
$('ul.selected li:eq(1)').attr('title');

closest doesn't work because it searches in the the element itself and it's parents, and you need to search inside it's childrens.

eq matches a single element by its index, and is zero based.

eKek0
Man i feel so dumb. Thank you !
Lee
This is far from ideal though, because he has to know (and hard-code) the index of the list item. I think the other answers are more appropriate.
Josh Stodola
"You have not to" hahaha I just *had* to up-vote that one.
Josh Stodola
@Stodola: "it will always be the second list item.", so this answer will works fine. Besides, this is the same as using :first alone
eKek0
A: 
$("ul.selected li[title]").attr('title');

Will return the value of the first <li> that has a title in the <ul> (Note: all <li> elements with a title will be wrapped in the jQuery object). This solution is flexible and doesn't rely on the particular hard-coded position of any particular <li> element

Russ Cam
+4  A: 

You can specify that the element should have a specific attribute:

$('ul.selected li[title]').attr('title')

If you have a lot of li elements with title in the list, you might want to limit the search to the first match. The attr method still only gets the attribute value from the first element, but there is no point in putting a lot of elements in the jQuery result that you won't use:

$('ul.selected li[title]:first').attr('title')
Guffa
+1 for the edit to include `:first` because the question here is about finding the "closest" title.
Josh Stodola