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.