• 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 / CSS / Get all of an element’s parent elements up the DOM tree

Get all of an element’s parent elements up the DOM tree

Get all of an element’s parent elements up the DOM tree

Let’s look at how to get all parent elements of a specific element.

/*!
 * Get all of an element's parent elements up the DOM tree
 * (c) 2021 Chris Ferdinandi, MIT License, https://gomakethings.com
 * @param  {Node}     elem     The element
 * @param  {Function} callback The test condition
 * @return {Array}             The parent elements
 */
function getParents (elem, callback) {

	// Setup variables
	let parents = [];
	let parent = elem.parentNode;
	let index = 0;

	// Make sure callback is valid
	if (typeof callback !== 'function') {
		callback = null;
	}

	// Get matching parent elements
	while (parent && parent !== document) {

		// If using a selector, add matching parents to array
		// Otherwise, add all parents
		if (callback) {
			if (callback(parent, index, elem)) {
				parents.push(parent);
			}
		} else {
			parents.push(parent);
		}

		// Jump to the next parent node
		index++;
		parent = parent.parentNode;

	}

	return parents;

}

Source

https://vanillajstoolkit.com/helpers/getparents/

CSS

Related Snippets:

  • Check if HTML element has class
  • Apply a CSS animation to an element with JavaScript
  • Add, remove, toggle, and check for the presence of a class
  • Toggle a Class of an Element

Primary Sidebar

Popular Posts

Story Generator

IP Grabber – get a users IP address with JavaScript

Simple Calendar

Remove Ads

Astrological Calculator

Copyright © 2023 JavaScriptSource.com

  • About
  • Privacy Policy
  • FAQ
  • Jobs For Developers