Explain Codes LogoExplain Codes Logo

How to get child element by class name?

javascript
dom-navigator
mutation-observer
dom-manipulation
Nikita BarsukovbyNikita Barsukov·Oct 1, 2024
TLDR

To retrieve a child element marked by a specific class, use querySelector('.child-class') on the parent element. The first matching child is effectively retrieved:

let child = document.getElementById('parent').querySelector('.child-class');

If you wish to get all child elements under that class, swap to using querySelectorAll:

let children = document.getElementById('parent').querySelectorAll('.child-class');

Now, child is your first match while children forms a collection of all matched instances under the parent.

Using ':scope' for direct child targeting

Running into deep DOM trees can get a bit messy, can't it? Keep it tidy by using direct child selection with :scope and >:

// So much for family secrets, eh? let directChildren = parentElement.querySelectorAll(':scope > .child-class');

The handy :scope pseudo-class represents the reference element scope where the method call happened, ensuring only direct children face the selection filter.

Performance and compatibility Overclocking

Pro tip: Stick with the least amount you require. If interested in the first child only, go for querySelector to avoid the hassle of fetching all elements with querySelectorAll.

As for browser compatibility, both querySelector and querySelectorAll are compatible down to IE9. If legacy browsers are your unfortunate reality, don't panic - you still have alternates like manual looping through childNodes and checking className properties.

Crafting a custom DOM navigator

Sometimes, off-the-shelf solutions won't do, especially when you need broad browser support or tight control. Here's a custom-made function that navigates the elements:

// Introducing, nature's gift to elements: Recursion! function findElementsByClassName(rootElement, className) { var foundElements = []; var elementsToSearch = [rootElement]; while (elementsToSearch.length > 0) { var currentElement = elementsToSearch.shift(); if (currentElement.classList.contains(className)) { foundElements.push(currentElement); } Array.prototype.push.apply(elementsToSearch, currentElement.children); } return foundElements; } let foundChildren = findElementsByClassName(document.getElementById('parent'), 'child-class');

This recursive marvel will negotiate its way through nested elements while working great with a wider variety of browsers.

Dealing with Multi-Class Kids and Early Breaks

Often, elements will cling to multiple classes like kids to candy. You'll need thunderous precision to target the right class:

function getByClass(targetClass, parentElement = document) { var children = parentElement.children, element; for (var i = 0; i < children.length; i++) { if (children[i].classList.contains(targetClass)) { element = children[i]; break; // Found it! Let's wrap up early and catch that game, shall we? } } return element; }

Early break: When found, stop! Let's not waste time looping around aimlessly.

Advanced Search: Spying on Dynamic DOM changes

Modern web apps are all about dynamically changing DOM elements. The MutationObserver API lets you peep into these changes and act as needed:

let observer = new MutationObserver(mutations => { mutations.forEach(mutation => { if (mutation.type === 'childList') { // Element(s) have been added or removed. Now, adjust search methods accordingly. Sneaky, eh? } }); }); observer.observe(document.getElementById('parent'), { childList: true });