Find the element parent with class ‘X’

Whilst at work an interesting question was posed to me “Can you find a node’s parent that has a specific class, only using pure javascript?”. Well of course my first thought was this is simple enough surely google has the answer and unsurprisingly it did, only the common theme involved loading jquery or another framework. This was needed for a simple script that would be loaded into the top of a lightweight page, loading a framework just to¬†accomplish¬†this simple task would be heavy handed.

So twenty minutes later I had thrown this snippet together

* Find Parent by class
* @param {HTMLElement} nd Start node (this will be checked for the search class)
* @param {String} cls The class that the parent should have
* @param {Function} [cback] A callback function that will be passed the found parent node
function findParent(nd, cls, cback) {
	//check to see if we have reached the top of the dom or fallen out
	if (nd === document || nd === window || typeof nd === 'undefined') {
		return false;

	//Convert a class search string into a testable regex
	if (typeof cls === 'string') {
		//Wrap the search so it will only find the whole word, don't forget to escape the backslash
		cls = new RegExp('(?:^|\\s)(' + cls + ')(?:$|\\s)', 'g');

	//Check the current nd classname with our search regex
	if (cls.test(nd.className)) {
		//Check to see if a callback function was passed
		if (typeof cback === 'function') {
			//Call the the passed function with the found node
		return true;

	if (nd.parent != false) {
		//This node has a parent, function calls itself passing the node parent
		return findParent(nd.parentNode, cls, cback);

	return false;

This code is reliant on recursion to move up the DOM tree parent to parent until it either hits the body or window. It could have been achieved with a while loop but let’s face it recursion is so much more fun and more importantly easier to break down each step.

An example of the code in practice can be found as a jsFiddle

Leave a Reply