views:

314

answers:

2

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)
A: 

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.

Andy Mikula
I tried that way without any luck, but $('#' + opt.name + ' > li[id$=' + opt.list[i].ID + ']') did the trick. Thank you!
Raúl Roa
+4  A: 

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.

John Kugelman
+1 -- and I'd try to give you +2 if you'd boldface "Element IDs should be unique"
kdgregory
In a perfect world where you don't work on others code: You are right. BUT, I'm working on code emulating a server side combobox using an unordered list. The list elements get generated dinamically from a datasource, therefore the ul output will be always the same when two server controls have the same datasource.I can control the ul id but not the one from it's li elements. Since selections should be control independent I need to be able to use this complex selector.
Raúl Roa