Skip to main content Accessibility Feedback


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,
 * @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

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


	return siblings;