Raúl Roa
Raúl Roa

Reputation: 12396

Selecting li from unordered list using ul and li id's

I'd like to obtain a li item from an unordered list using the id attribute of both elements as part of the selector.

This is an example of how I made it work using the ul css class:

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

I tried to use the following approach with no luck:

var listItem = $("#" + opt.name).childs.find("#" + opt.list[i].ID)

Upvotes: 0

Views: 1318

Answers (2)

John Kugelman
John Kugelman

Reputation: 362197

There shouldn't be any need for a complex selector/lookup when you're using IDs. Element IDs should be unique across the entire document, so finding an element is as simple as

var listItem = $("#" + opt.list[i].ID);

If that doesn't work I suggest fixing up your IDs so they are unique rather than working around the problem with an unnecessarily complex CSS selector.

Upvotes: 4

Andy Mikula
Andy Mikula

Reputation: 16770

You should be able to do something like this:

var listItem = $('#' + opt.name + ' > li#' + opt.list[i].ID);

which should select li elements that are children of the first.

See the documentation here: jQuery Selectors: Parent/Child.

Upvotes: 1

Related Questions