Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

179
Views
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>

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

we can use is method to check if two elements are the same or not.

so, a solution would have two variables, one is the currently selected element and one is the first element.

let selectedItem = $('.list').find('.item.selected');
let firstElement = $('.list').find('.item:first');

console.log($(selectedItem).is(firstElement)); // this returns true, false

jsfiddle

about 4 years ago · Juan Pablo Isaza Report

0

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>

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!