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?
If you have HTML inside the LI elements and you only want to get the text, you need innerText or textContent .
document. querySelectorAll("ul > li");
<li>: The List Item element. The <li> HTML element is used to represent an item in a list. It must be contained in a parent element: an ordered list ( <ol> ), an unordered list ( <ul> ), or a menu ( <menu> ). In menus and unordered lists, list items are usually displayed using bullet points.
Not sure if the DOM API exposes that, but you could do...
$('ul').on('click', 'li', function() {
var label = String.fromCharCode(97 + $(this).index());
});
jsFiddle
...if you had under 26 elements. If you have more, you would need to use a more complicated algorithm, typically known as the Excel Row to Column algorithm.
$('ul').on('click', 'li', function() {
var index = $(this).index() + 1;
var label = '';
var mod;
while (index) {
mod = (index - 1) % 26;
label = String.fromCharCode(97 + mod) + label;
index = Math.floor((index - mod) / 26);
}
});
jsFiddle
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With