sameold
sameold

Reputation: 19242

How to select first child?

How do I select the first div in these divs (the one with id=div1) using first child selectors?

<div class="alldivs">
   <div class="onediv" id="div1"> 1 This one </div>
   <div class="onediv" id="div2"> 2 </div>
   <div class="onediv" id="div3"> 3 </div>
</div>

Upvotes: 38

Views: 147693

Answers (6)

MD Mahmudul Hasan
MD Mahmudul Hasan

Reputation: 389

if you have to find what first child text then this is the easiest solution for you

  $(".openReceipt").on("click", function() {
        console.log($(this).eq(0).find(".test").text());
    })

Upvotes: 2

Roko C. Buljan
Roko C. Buljan

Reputation: 206028

In plain JavaScript you would use something like:

// Single
document.querySelector(".onediv").classList.add("red"); 

// Multiple (deeply nested)
document.querySelectorAll(".onediv:first-child").forEach(EL => EL.classList.add("red"));

Or by Parent Element using Element.firstElementChild:

// Single Parent 
document.querySelector(".alldivs").firstElementChild.classList.add("red");

// Multiple parents
document.querySelector(".alldivs").forEach(EL => EL.firstElementChild.classList.add("red"));

jQuery get first child

Use: $(".onediv").eq(0)

Other examples of selectors and methods targeting the first LI inside an UL:

Syntax Type Example
.eq() Method $("li").eq(0)
.first() Method $("li").first()
:eq() Selector $("li:eq(0)")
:first Selector $("li:first")
:first-child Selector $("li:first-child")
:lt() Selector $("li:lt(1)")
:nth-child() Selector $("li:nth-child(1)")
.slice() Method $("li").slice(0,1)

There are some slight differences in how they operate regarding depth. Play with the below demo examples:

$("select").on("change", function() {
  $("li").removeClass("red");
  new Function(`return (${this.value})`)();
}).trigger("change");
.red {color: red;}
option[disabled] {font-size: 1.4em; color: blue;}
<select>
  <option disabled>jQuery examples:</option>

  <option>$("li").eq(0).addClass("red")</option>
  <option>$("li:eq(0)").addClass("red")</option>
  <option>$("li").first().addClass("red")</option>
  <option>$("li:first").addClass("red")</option>
  <option>$("li:first-child").addClass("red")</option>
  <option>$("li:lt(1)").addClass("red")</option>
  <option>$("li:nth-child(1)").addClass("red")</option>
  <option>$("li").slice(0,1).addClass("red")</option>

  <option disabled>JavaScript examples:</option>

  <option>document.querySelector("li").classList.add("red")</option>
  <option>document.querySelectorAll("li:first-child").forEach(EL => EL.classList.add("red"))</option>

  <option disabled>Mixed jQuery + JavaScript</option>

  <option>$("li")[0].classList.add("red")</option>
</select>

<ul>
  <li>1</li>
  <li>2
    <ul>
      <li>2.1</li>
      <li>2.2</li>
    </ul>
  </li>
  <li>3</li>
</ul>

<script src="https://code.jquery.com/jquery-3.6.0.js"></script>

you can also use [i] to get the JS Element by index out of the jQuery elements collection like eg:

$("li")[0]

but now that you have the native JS Element representation you have to use JavaScript methods eg:

$("li")[0].classList.add("active"); // Adds class "active" to the first LI in the DOM

or you can (don't - it's bad design) wrap it back into a jQuery object

$( $("li")[0] ).addClass("active"); // Don't! Use .eq() instead

Upvotes: 54

Krishnamoorthy Acharya
Krishnamoorthy Acharya

Reputation: 4244

Hi we can use default method "first" in jQuery

Here some examples:

When you want to add class for first div

  $('.alldivs div').first().addClass('active');

When you want to change the remove the "onediv" class and add only to first child

   $('.alldivs div').removeClass('onediv').first().addClass('onediv');

Upvotes: 1

Prabhakar
Prabhakar

Reputation: 6754

As @Roko mentioned you can do this in multiple ways.

1.Using the jQuery first-child selector - SnoopCode

   $(document).ready(function(){
    $(".alldivs onediv:first-child").css("background-color","yellow");
        }
  1. Using jQuery eq Selector - SnoopCode

     $( "body" ).find( "onediv" ).eq(1).addClass( "red" );
    
  2. Using jQuery Id Selector - SnoopCode

       $(document).ready(function(){
         $("#div1").css("background-color: red;");
       });
    

Upvotes: 0

Frederik Wordenskjold
Frederik Wordenskjold

Reputation: 10221

$('div.alldivs :first-child');

Or you can just refer to the id directly:

$('#div1');

As suggested, you might be better of using the child selector:

$('div.alldivs > div:first-child')

If you dont have to use first-child, you could use :first as also suggested, or $('div.alldivs').children(0).

Upvotes: 22

alex
alex

Reputation: 490153

Use the :first-child selector.

In your example...

$('div.alldivs div:first-child')

This will also match any first child descendents that meet the selection criteria.

While :first matches only a single element, the :first-child selector can match more than one: one for each parent. This is equivalent to :nth-child(1).

For the first matched only, use the :first selector.

Alternatively, Felix Kling suggested using the direct descendent selector to get only direct children...

$('div.alldivs > div:first-child')

Upvotes: 10

Related Questions