<div class="bg-1">
	.bg-1
	<div class="bg-2">
		.bg-2
		<div class="bg-3">
			.bg-3
			<div class="bg-4">
				.bg-4
				<div class="bg-5">
					.bg-5
					<div class="bg-6">
						.bg-6
						<div class="bg-7">
							.bg-7
						</div>
					</div>
				</div>
			</div>
		</div>
	</div>
</div>
.bg-1,
.bg-2,
.bg-3,
.bg-4,
.bg-5,
.bg-6,
.bg-7 {
	color: #ffffff;
	margin: 0.5em 0;
	padding: 0.5em 1em;
}

.bg-1 {
	background-color: #001f3f;
}

.bg-2 {
	background-color: #0074d9;
}

.bg-3 {
	background-color: #3d9970;
}

.bg-4 {
	background-color: #ff851b;
}

.bg-5 {
	background-color: #ff4136;
}

.bg-6 {
	background-color: #f012be;
}

.bg-7 {
	background-color: #111111;
}
var levelsUp = function (elem, selector, distance) {

	// If distance isn't defined yet, set it to 0
	if (!distance) {
		distance = 0;
	}

	// Increase the distance by 1
	distance++;

	// Get the parent of the current element
	var parent = elem.parentNode;

	// If you we reach an element with no matches() method, bail
	if (!parent.matches) return -1;

	// If we've reached the parent, return the distance
	if (parent.matches(selector)) return distance;

	// Otherwise, recursively run levelsUp() again
	return levelsUp(parent, selector, distance);

};

var start = document.querySelector('.bg-7');

console.log(levelsUp(start, '.bg-5'));
console.log(levelsUp(start, '.bg-1'));
console.log(levelsUp(start, '.bg-3'));
console.log(levelsUp(start, '.nope'));

External CSS

This Pen doesn't use any external CSS resources.

External JavaScript

This Pen doesn't use any external JavaScript resources.