Raúl Roa
Raúl Roa

Reputation: 12396

jQuery selector to obtain li object from specific unordered list

I'm trying to obtain a specific li element from a unordered list.

I'm doing it this way:

var listItem = $('ul.selectedItems').filter(list[i].ID);

Any idea of why this isn't working?

Upvotes: 1

Views: 4744

Answers (3)

eKek0
eKek0

Reputation: 23339

I think you can do something like this:

  $("ul.selectedItems li").each(function(){
    if ($(this).is('#mypreferedid')) {
       //do something here
       return false; //to stop cycling
    }
  });

If you don't know the id of the element, but you know it's position you can do this:

  $("ul.selectedItems li").each(function(index, element){
    if (index == selectedPosition) {
       //do something here
       return false; //to stop cycling
    }
  });

Upvotes: 0

SLaks
SLaks

Reputation: 888303

The filter method takes a regular jQuery selector, so you should be writing filter("#"+list[i].ID). (Assuming that list[i].ID is the id attribute of an li element). Also, the filter method searches the elements contained in your jQuery object, not their children; you should be calling the children method instead. See the documentation.


However, the best way to do it is like this:

var listItem = $('ul.selectedItems li#' + list[i].ID);

For more information on jQuery selectors, see here.

Upvotes: 3

Daniel Moura
Daniel Moura

Reputation: 7956

This returns only the ul, your selector should return li's

var listItem = $('ul.selectedItems li').filter(list[i].ID);

But if you have the li's id you can do this

var listItem = $('#' + liId);

Upvotes: 1

Related Questions