neubert
neubert

Reputation: 16792

seeing what nth child a particular element corresponds to?

Using the example at https://api.jquery.com/eq/, let's say I have the following HTML:

<ul>
  <li>list item 1</li>
  <li>list item 2</li>
  <li>list item 3</li>
  <li>list item 4</li>
  <li>list item 5</li>
</ul>

If you want to select the second <li> you can do $("li").eq( 2 ).

But what if I had a random <li> and wanted to see if it was the first? eg. Let's say I did var el = $("li").eq(Math.floor(Math.random() * 5) + 1) and then wanted to see if el was the first <li>. How would I do that?

Upvotes: 1

Views: 62

Answers (2)

charlietfl
charlietfl

Reputation: 171679

One approach is use index() to get an elements index within it's siblings.

You can also use is() and pass in a a selector or jQuery object representing a specific element

const $li = $('li')

 $li.eq(Math.floor(Math.random()*5)).css('color','red').click(function(){
   const index = $(this).index();
   console.log('My index is ',index , 'is first = ', index ===0);
   console.log('I am first', $(this).is($li.first()))
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul>
  <li>list item 1</li>
  <li>list item 2</li>
  <li>list item 3</li>
  <li>list item 4</li>
  <li>list item 5</li>
</ul>

Upvotes: 0

CertainPerformance
CertainPerformance

Reputation: 370689

You can check whether the element .matches a nth-child selector you're interested in. For example:

const li = $('li').eq(2)[0]; // .eq is 0-indexed
console.log(
  li.matches(':nth-child(2)'), // false - it's the 3rd (1-indexed), not the 2nd
  li.matches(':nth-child(3)') // true
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul>
  <li>list item 1</li>
  <li>list item 2</li>
  <li>list item 3</li>
  <li>list item 4</li>
  <li>list item 5</li>
</ul>

I prefer using plain DOM elements, but if you have to use a jQuery method to see if the element matches a selector, use .is:

const $li = $('li').eq(2); // .eq is 0-indexed
console.log(
  $li.is(':nth-child(2)'), // false - it's the 3rd (1-indexed), not the 2nd
  $li.is(':nth-child(3)') // true
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul>
  <li>list item 1</li>
  <li>list item 2</li>
  <li>list item 3</li>
  <li>list item 4</li>
  <li>list item 5</li>
</ul>

No need for jQuery, this is trivial without it:

const li = document.querySelectorAll('li')[2]; // 0-indexed collection
console.log(
  li.matches(':nth-child(2)'), // false - it's the 3rd (1-indexed), not the 2nd
  li.matches(':nth-child(3)') // true
);
<ul>
  <li>list item 1</li>
  <li>list item 2</li>
  <li>list item 3</li>
  <li>list item 4</li>
  <li>list item 5</li>
</ul>

Upvotes: 2

Related Questions