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.
Two problems:
getElementsByClassName returns an array-like object. You need to select the first element in the list.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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With