Skip to main content Accessibility Feedback

getPreviousUntil.js

Get all previous siblings of an element until a test condition is met.

/*!
 * Get previous siblings of an element until a selector is found
 * (c) 2021 Chris Ferdinandi, MIT License, https://gomakethings.com
 * @param  {Node}   elem     The element
 * @param  {Function} callback The test condition
 * @return {Array}           The siblings
 */
function getPreviousUntil (elem, callback) {

	// Setup siblings array and get previous sibling
	let siblings = [];
	let prev = elem.previousElementSibling;
	let index = 0;

	// Loop through all siblings
	while (prev) {

		// If the matching item is found, quit
		if (callback && typeof callback === 'function' && callback(prev, index, elem)) break;

		// Otherwise, push to array
		siblings.push(prev);

		// Get the previous sibling
		index++;
		prev = prev.previousElementSibling;

	}

	return siblings;

}