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
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
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.
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;
}
$('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());
};
});