DEV Community

Cover image for Select the direct children of an element
Phuoc Nguyen
Phuoc Nguyen

Posted on • Originally published at phuoc.ng

2

Select the direct children of an element

When we use the querySelectorAll function to select all children of a given element, it fetches all the children, including the nested ones. But what if you only want to retrieve the direct children? That's where the > selector comes in handy.

To make things clearer, here's an example: let's say you want to select all direct children of an element with the ID of parent. You can simply use the following code:

const parentElement = document.getElementById('parent');
const directChildren = parentElement.querySelectorAll('> *');
Enter fullscreen mode Exit fullscreen mode

In the code above, we're using getElementById to select a parent element with a specific id attribute. Then, we use querySelectorAll to choose all direct children of that parent element using the > selector. The * selector matches any element, so this code selects all direct children, no matter their tag name.

If you only want to select a specific type of tag, you can use that tag name instead of the * selector. For example, the following code selects only the li tags that are direct children of a given ul element.

This approach excludes any nested li tags.

const ul = document.getElementById('list');
const directItems = ul.querySelectorAll('> li');
Enter fullscreen mode Exit fullscreen mode

If you found this series helpful, please consider giving the repository a star on GitHub or sharing the post on your favorite social networks 😍. Your support would mean a lot to me!

If you want more helpful content like this, feel free to follow me:

SurveyJS custom survey software

Simplify data collection in your JS app with a fully integrated form management platform. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more. Integrates with any backend system, giving you full control over your data and no user limits.

Learn more

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay