How do I select the first child of a parent element?
I am trying to select the first pure JavaScript parent and change some of its CSS properties. I've tried methods .firstChild
and .childNodes[1]
, but they don't work. This can be done with a CSS selector nth-child()
, 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 css property.</div>
<div class="child"></div>
<div class="child"></div>
<div class="child"></div>
</div>
What I have 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 would be appreciated.
source to share
for better browser support for your request, you can use pure CSS with a selector :first-child
as it is cross browser and it is CSS 2.1 , see this link here and the table below illustrates browser support:
so here is a snippet with ONLY CSS :
.child:first-child {
/*whatever CSS you want here --
just fot visualization and snippet :*/
background-color: red;
color: white;
}
<div class="daddy">
<div class="child">I want select this child and change it css property.</div>
<div class="child">child 2</div>
<div class="child">child 3</div>
<div class="child">child 4</div>
</div>
source to share
Two problems:
-
getElementsByClassName
returns an object like an array. You need to select the first item in the list. -
firstChild
andchildNodes
will return text nodes, not just elements. Use.children
only to access elements:
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>
source to share
getElementsByClassName
returns a nodeList, it has no property firstChild
or childNodes
, you have to get the elements of the collection and then use those properties, i.e. x[index]
...
var x = document.getElementsByClassName('daddy'), i = 0, j;
for (; i < x.length; i++) {
e = x[i].childNodes;
for (j = 0; j < e.length; j++) {
if (e[j].nodeType === 1) {
e[j].style.width = '5em';
break;
}
}
}
Please note that only newer browsers (including IE9) support the method getElementsByClassName
. If you want to support older browsers, you must either reinforce the method or use an alternative function. The question answers provide several solutions.
Alternatively, you can also use the method querySelectorAll
:
[].slice.call(document.querySelectorAll('.daddy > .child:first-child'))
.forEach(function(e) {
e.style.width = '5em';
});
source to share