views:

77

answers:

1

If I've got a ul with 3 items in it and the list-style-type is set to lower-alpha, I end up with this

a. Item 1

b. Item 2

c. Item 3

With jQuery, I can easily get the value of any item you click - "Item 1" if I click the first. But can I get the list item label? In this case a?

+5  A: 

Not sure if JavaScript exposes that, but you could do

$('li').each(function(i) {

    $(this).click(function() {

        var item = String.fromCharCode(97 + i);
        alert(item);
    });

});

What this does it attach a click event to each li, and has the value i set as its index.

When you click one, it gets the lowercase a which has 97 charCode, and then adds the index which gives you a letter.

See an example on JSbin.

Note After 26 list items, you are going to get characters like {, etc, whereas using CSS's lower-alpha will give you aa, ab etc. (see example on JSbin). You would need to modify the code to suit if you had more than 26 list items.

alex