• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar
JavaScriptSource

JavaScriptSource

Search 5,000+ Free JavaScript Snippets

  • Home
  • Browse Snippets
    • Addon
    • Ajax
    • Buttons
    • Cookies
    • CSS
    • Featured
    • Forms
    • Games
    • Generators
    • Image Effects
    • Math Related
    • Miscellaneous
    • Multimedia
    • Navigation
    • Page Details
    • Passwords
    • Text Effects
    • Time & Date
    • User Details
Home / Miscellaneous / Get all direct descendant elements that match a test

Get all direct descendant elements that match a test

Get all direct descendant elements that match a test

To do this, we need to combine Node.children with a few other techniques.

We can use Array.from() to turn the NodeList that Node.children returns into an array, and then use the Array.filter() method to remove an elements that don’t match a test we specify.

/*!
 * Get all direct descendant elements that match a test condition
 * (c) 2021 Chris Ferdinandi, MIT License, https://gomakethings.com
 * @param  {Node}   elem     The element to get direct descendants for
 * @param  {Function} callback The test condition
 * @return {Array}           The matching direct descendants
 */
function childrenMatches (elem, callback) {
	return Array.from(elem.children).filter(callback);
}

Source

https://vanillajstoolkit.com/helpers/childrenmatches/

Miscellaneous

Related Snippets:

  • Detect If an Element has focus
  • Insert an element before another one
  • Combine all items in an array into a string
  • Get unique values in an array

Primary Sidebar

Popular Posts

Story Generator

IP Grabber – get a users IP address with JavaScript

Simple Calendar

Remove Ads

Astrological Calculator

Copyright © 2025 JavaScriptSource.com

  • About
  • Privacy Policy
  • FAQ
  • Jobs For Developers