Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to detect whether the element is the first child with the given class

I am trying to detect if the selected element is the first child with the given class with jQuery. In the example, you can see that it is the first child with class .item but the selector :first-of-type doesn’t work for that because it is not the first div.

How can this be solved?

var selectedItem = $('.list').find('.item.selected');
var isFirst = selectedItem.is(':first-of-type');

console.log('Is item first? ' + isFirst);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="list">
  <div class="search"></div>
  <div class="item selected">Item 1</div>
  <div class="item">Item 2</div>
  <div class="item">Item 3</div>
</div>

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Using jquery’s .index() overload you can apply it to a predefined collection (jquery object):

var isFirst = $(".list .item").index($('.list .item.selected')) == 0;

Updated snippet:

var items = $(".list .item");
var selectedItem = $('.list .item.selected');

var isFirst = items.index(selectedItem) == 0;
console.log(isFirst)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="list">
  <div class="search"></div>
  <div class="item selected">Item 1</div>
  <div class="item">Item 2</div>
  <div class="item">Item 3</div>
</div>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading