HOWTO · JavaScript
How to Get Child Element by Class in JavaScript
Learn how to select one or multiple descendant elements by class in JavaScript, including matching one class token or requiring multiple class tokens on the same element.
On this page
To select elements with a given class inside a parent, call querySelector() for the first match or querySelectorAll() for every match. These searches include all matching descendants, including nested elements. If you need direct children only, use a :scope > selector. The examples below also show getElementsByClassName() and how child properties differ from class-based searches.
Get Child Element by class in JavaScript
Choose the API based on the result you need: querySelector() returns one element or null; querySelectorAll() returns a static NodeList; getElementsByClassName() returns a live HTMLCollection. document.getElementById() is useful for finding the parent, while firstElementChild, lastElementChild, and children access element children without filtering by class. All parent-scoped searches discussed here can include nested descendants unless the selector explicitly restricts the match to direct children.
Use querySelector() to Get Child Element by class Name in JavaScript
Use a CSS class selector, which starts with a dot, on the parent element. The standalone JavaScript example below filters an array of objects by checking whether each object’s classes array contains the item token; it does not query the DOM. Check that the parent and result exist before reading a property in the browser example that follows, since either lookup can return null.
For a quick view of matching a class token across several elements, run this JavaScript example:
const elements = [
{ text: 'One', classes: ['item', 'featured'] },
{ text: 'Two', classes: ['item'] },
{ text: 'Note', classes: ['note'] }
];
const matches = elements.filter(element => element.classes.includes('item'));
console.log(matches.map(element => element.text).join(', '));
One, Two
This self-contained browser page demonstrates first-match selection, all-match selection, element-child properties, class-name lookup, and a direct-child selector. It is a browser example and has not been executed in the supplied runtime snapshot.
<!doctype html>
<html lang="en">
<body>
<ul id="parent">
<li class="item featured">One</li>
<li class="item">Two</li>
<li class="item"><span class="item">Nested three</span></li>
</ul>
<script>
const parent = document.getElementById('parent');
const first = parent?.querySelector('.item');
console.log(first?.textContent); // One
const matches = parent?.querySelectorAll('.item') ?? [];
const lastItem = matches.length ? matches[matches.length - 1] : null;
console.log(lastItem?.textContent.trim() ?? 'No matching item'); // Nested three
console.log([...matches].map(element => element.textContent.trim()));
const firstElement = parent?.firstElementChild;
const lastElement = parent?.lastElementChild;
const childElements = parent?.children;
console.log(firstElement?.textContent.trim(), lastElement?.textContent.trim());
console.log(childElements?.length); // 3 direct element children
const classMatches = parent?.getElementsByClassName('item');
console.log(classMatches?.length); // 4 matching descendants
const directMatches = parent?.querySelectorAll(':scope > .item') ?? [];
console.log(directMatches.length); // 3 direct matches
</script>
</body>
</html>
The selector .item matches an element carrying that class token, whether or not it has other classes too. querySelector() always returns only the first matching descendant in document order; it does not by itself retrieve the last arbitrary match. In the browser example, querySelectorAll('.item') gathers matches and the length check selects the final entry only when one exists. With the supplied markup, that final match is the nested span containing “Nested three.” If there is no match, the guarded expression keeps lastItem as null and logs No matching item. If two class tokens must both be present, write a selector such as .item.featured with no space. A space means a descendant relationship in CSS selectors, not “either class.”
Use querySelectorAll() Method to Get All Child Nodes Having the Same class in JavaScript
Call parent.querySelectorAll('.item') to get all descendant elements matching that class selector, then iterate over the returned NodeList. The example’s nested span is included because it also has item. If only direct children should match, use the :scope approach in the final section.
The NodeList returned by querySelectorAll() is static: it records matches at the time of the call and does not update after later DOM changes. Call the method again to obtain a fresh set. Invalid selector syntax causes a SyntaxError DOMException; it does not return a string such as SYNTAX_ERR. Ensure selector text is valid CSS, especially when constructing it from a class name that contains punctuation.
Use document.getElementById() With Child Nodes’ Properties in JavaScript
document.getElementById('parent') locates the parent by its unique id; it does not search for a child class. Once you have the parent, firstElementChild and lastElementChild return its first and last element children. children provides the collection of its direct element children. These properties do not filter by class, and they exclude text nodes such as whitespace between HTML tags. Use them when position or all direct element children are what matters; use a selector or class-name method to filter by class.
Use getElementsByClassName() Method to Get One or Multiple Child Elements by class Name in JavaScript
Call parent.getElementsByClassName('item') with the class name and no leading dot. It returns all matching descendant elements, including nested ones. To require multiple class tokens, pass them separated by spaces, as in getElementsByClassName('item featured'); the element must have every listed class. This API returns a live HTMLCollection, so its length and members reflect matching DOM changes. If you need a stable snapshot while changing the DOM, copy the collection with Array.from(...) before iterating.
Use :scope to Get Direct Children in JavaScript
Prefix the selector with :scope > to match only elements directly under the parent. For example, parent.querySelectorAll(':scope > .item') excludes the nested span.item, while parent.querySelectorAll('.item') includes it. The > combinator expresses the direct-child relationship; without it, a class selector searches deeper descendants too. This distinction is the key choice when “child” means immediate child rather than any element nested somewhere inside the parent.