How to find li index in javascript

Viewed 183

How to find li index using javascript .I have MARK UP this

<ul class="rh02nav">
               <li><a class="" href="#1" title="View Slide 1"><b>View Slide 1</b></a></li>
               <li><a class="o-hf rh02cnav" href="#2" title="View Slide 2 rh02cnav"><b>View Slide 2</b></a></li>
               <li><a class="o-hf " href="#3" title="View Slide 3"><b>View Slide 3</b></a></li>
               <li><a class="o-hf " href="#4" title="View Slide 4"><b>View Slide 4</b></a></li>
               <li><a class="o-hf " href="#5" title="View Slide 5"><b>View Slide 5</b></a></li>
            </ul>

I am able to find parent li li. But I want it's index.

// working fine
console.log('Element',document.querySelector('.rh02nav .rh02cnav').parentElement)

// not working expected 1 .output -1
console.log(Array.prototype.indexOf.call(document.querySelector('.rh02nav li'), document.querySelector('.rh02nav .rh02cnav').parentElement))

Here is my full code :
https://jsbin.com/luzuvisuvu/3/edit?html,js,console,output

2 Answers
let parent = document.querySelector('.rh02nav .rh02cnav').parentElement;
let childern = [...parent.children];
let index;
for(let i in children) 
if(children[i].classList.contains("rh02cnav") {
    index = i;
    break;
}

console.log(index);

it works if the className is unique

Loop through the child li elements and see if the anchor tag inside them includes the right className:

let children = document.querySelector('ul.rh02nav').children
let idx
for (let i = 0; i < children.length; i++) {
  if (children[i].querySelector('a').className.includes('rh02cnav')) {
    idx = i
  }
}

console.log('idx is ' + idx)
<ul class="rh02nav">
  <li><a class="" href="#1" title="View Slide 1"><b>View Slide 1</b></a></li>
  <li><a class="o-hf rh02cnav" href="#2" title="View Slide 2 rh02cnav"><b>View Slide 2</b></a></li>
  <li><a class="o-hf " href="#3" title="View Slide 3"><b>View Slide 3</b></a></li>
  <li><a class="o-hf " href="#4" title="View Slide 4"><b>View Slide 4</b></a></li>
  <li><a class="o-hf " href="#5" title="View Slide 5"><b>View Slide 5</b></a></li>
</ul>

Related