简体   繁体   中英

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)

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.

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM