views:

41

answers:

3

Hello everyone,

i need to get number of order highlighted element (by javascript, jquery):

<li>A</li>
<li>B</li>
<li class="highlight">C</li>
<li>D</li>

so, in this case i want to get number 3 into my variable.

Thanks

+4  A: 

Use Index:

var highlighted = $('li').index($('.highlight'));

Note: since index will be 0 based, this will return 2. If you need 3 instead, just add 1.

rosscj2533
A: 

Or plain js:

var index;
var lis = document.getElementsByTagName("li");
        for (var i = 1; i < lis.length; i++) {
            if (lis[i].className == "highlight") {
                alert("this index: " + i);
                index = i; 
            }
poo
A: 
$('li').each(function(index) {
  if ($(this).hasClass('highlight')){
    alert(index);
  };
});

Note: since index will be 0 based, this will return 2. If you need 3 instead, just add 1 to index.

$('li').each(function(index) {
      if ($(this).hasClass('highlight')){
        alert(index+1 + ': '+ $(this).text());
      };
    });
lukemh