title: jQuery Closest Relative
body: <p>I encountered this question in a "famous" online interviewing website:</p>
  
  <blockquote>
    <p>The following XML represents a family tree:</p>
  </blockquote>
  
  <pre><code>&lt;James&gt;
       &lt;Dave&gt;&lt;/Dave&gt;
       &lt;Mike&gt;&lt;/Mike&gt;
       &lt;Sarah&gt;&lt;/Sarah&gt; 
  &lt;/James&gt; 
  </code></pre>
  
  <blockquote>
    <p>Implement the closestRelative function so that it returns the parent's closest relative whose name matches the
    relativeName and obays the following rules:</p>
    
    <p>The parent parameter is a jQuery selector of which the closest
    relative will be a descendant. Each member of the family, including
    children, may also be a parent to one or more children. Children are
    more closely related to the parent than grandchildren. If several
    children in the same generation have the same name then the first
    child in the tree is considered the closer. If no matching relative is
    found the function should return an empty jQuery object. For example,
    closestRelative($('James'), 'Mike') should return the jquery object
    wrapping <code>&lt;Mike&gt;&lt;/Mike&gt;</code>.</p>
    
    <p>ECMAScript 5.1, jQuery v3.1.1 (available as $)</p>
  </blockquote>
  
  <p>Because of jQuery's <code>find</code> search depth first, rather than breadth first as stated on the hints of the question; my first approach was wrong. Then I wrote a recursive function for <em>"breadth find"</em> as below:</p>
  
  <pre><code>function closestRelative(parent, relativeName) {
    firstLevel = $(parent).children();
    if (firstLevel.length) {
      result = $(firstLevel).filter(relativeName);
      if (result) {
        return result.first();
      } else {
        closestRelative(firstLevel, relativeName);
      }
    } else {
      return $([]);
    }
  
  }
  </code></pre>
  
  <p>The results of the test cases:</p>
  
  <blockquote>
    <p>Example case: Correct answer<br>
      Several generations: Wrong answer<br>
      Children with the same name: Wrong answer</p>
  </blockquote>
  
  <p>I couldn't find a solution which pass the all 3 test cases and I don't know what I'm missing because I'm already searching for several generations and returning the first child of encountered family members array. What is wrong with code and how can I test this function against the xml and get <code>&lt;Mike&gt;&lt;/Mike&gt;</code> as result?</p>
  
  <pre><code>var xml = $.parseXML("&lt;James&gt;&lt;Dave&gt;&lt;/Dave&gt;&lt;Mike&gt;&lt;/Mike&gt;&lt;Sarah&gt;&lt;/Sarah&gt;&lt;/James&gt;");
  console.log(closestRelative($(xml).children()[0], 'Mike')[0].outerHTML); //Something is wrong here
  </code></pre>
  
  <p><a href="https://jsfiddle.net/ros9cdvg/" rel="nofollow noreferrer">https://jsfiddle.net/ros9cdvg/</a></p>