Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I select the first child of a parent element?

I'm trying to select the first child of a parent element with pure JavaScript and change some of it's CSS properties. I've tried .firstChild and .childNodes[1] methods but they do not work. This can be done with CSS nth-child() selector but I would like to do it with JavaScript for better browser support.

Example:

HTML

    <div class="daddy">
       <div class="child">I want select this child and change it's css property.</div>
       <div class="child"></div>
       <div class="child"></div>
       <div class="child"></div>
    </div>

What I've tried:

JavaScript

    var x = document.getElementsByClassName('daddy');
    var d = x.firstChild; // and the x.childNodes[1]
    d.style.width="5em";

What works:

CSS

   daddy:nth-child(1) { width: 5em; }

Any help will be appreciated.

like image 876
basitmate Avatar asked Oct 26 '25 10:10

basitmate


1 Answers

Two problems:

  1. getElementsByClassName returns an array-like object. You need to select the first element in the list.
  2. firstChild and childNodes will return text nodes, not just elements. Use .children to access elements only:

var x = document.getElementsByClassName('daddy');
var d = x[0].children[0];
d.style.width="5em";
<div class="daddy">
  <div class="child">I want to select this child and change its css property.</div>
  <div class="child"></div>
  <div class="child"></div>
  <div class="child"></div>
</div>
like image 151
Paul Roub Avatar answered Oct 28 '25 22:10

Paul Roub



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!