Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Possible to get list item (<li>) label with JavaScript?

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?

like image 317
matthew Rhodes Avatar asked May 10 '10 03:05

matthew Rhodes


People also ask

How do I get text from Li?

If you have HTML inside the LI elements and you only want to get the text, you need innerText or textContent .

How do you select Li inside UL?

document. querySelectorAll("ul > li");

What is UL and Li in JavaScript?

<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.


1 Answers

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

like image 187
alex Avatar answered Sep 28 '22 06:09

alex