How to select first child?

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

Leave a Comment