Blyde Blyde - 7 months ago 26
Javascript Question

Finding child element of parent pure javascript

What would the most efficient method be to find a child element of (with class or ID) of a particular parent element using pure javascript only. No jQuery or other frameworks.

In this case, I would need to find child1 or child2 of parent, assuming that the DOM tree could have multiple child1 or child2 class elements in the tree. I only want the elements of parent

<div class="parent">
<div class="child1">
<div class="child2">


The children property returns an array of elements, like so:

parent = document.querySelector('.parent');
children = parent.children; // [<div class="child1">]

querySelector is relatively new and not supported in older browsers. There are alternatives, like document.getElementsByClassName('parent')[0] if you so desire.

Edit: Now that I think about it, you could just use querySelectorAll to get decendents of parent having a class name of child1:

children = document.querySelectorAll('.parent .child1');

The difference between qS and qSA is that the latter returns all elements matching the selector, while the former only returns the first such element.