Himmel
Himmel

Reputation: 3709

jQuery recursive search parent element for class

I'm boggled by what seems like strange behavior from JavaScript/jQuery in a simple function that I wrote to find a parent element by class name. The function is seemingly pretty straightforward in that it checks for a class on an element, if it doesn't find it, it calls the same function with the parent element... until it finds the class.

Here is the relevant JSFiddle, https://jsfiddle.net/xxvywa4v/.


Given the following HTML:

<div class="outer">
  <div class="inner">
    <div class="innermost">Click Me</div>
  </div>
</div>

and the following JavaScript:

function getParentByClass($el, className) { 
  if ($el.hasClass(className)) {
    console.log('found element!', $el); // returns correct element
    return $el;
  } else {
    getParentByClass($el.parent(), className);
  }
}

$('.innermost').on('click', function(e) {
  var $outerEl = getParentByClass($(e.target), 'outer');

  console.info($outerEl); // undefined
});

Why is the element correctly logged and found in getElementByClass, but is returned to the click handler as undefined?

(Note: I'm not interested in alternative ways to reproduce this functionality, but rather why it isn't working in this particular implementation)

Upvotes: 0

Views: 752

Answers (1)

juvian
juvian

Reputation: 16068

Small error, you are not actually returning what you found in the recursion. You are returning when you find it, but you are not bubbling it up to return that:

} else {
    getParentByClass($el.parent(), className);
}

You need to put a return there as well: return getParentByClass($el.parent(), className);

Upvotes: 1

Related Questions