Search code examples
jqueryparentchildren

jQuery traversal of HTML using .parent() instead of .closest()


Here is my simplified HTML:

<html>
<body>
<table>
 <tr>
  <td>
   <div id="link1">
    <a href="http://example.com?this=the+one+i+want">foo</a>
   </div>
  </td>
  <td>
   <div id="link2">
    <a href="http://example.com?this=bar">bar</a>
   </div>
  </td>
  <td>
   <div id="link3">
    <a href="http://example.com?this=baz" class="baz_anchor">baz</a>
   </div>
  </td>
 </tr>
 <tr>
  <td>
   <div id="link1">
    <a href="http://example.com?this=foo">foo</a>
   </div>
  </td>
  <td>
   <div id="link2">
    <a href="http://example.com?this=bar">bar</a>
   </div>
  </td>
  <td>
   <div id="link3">
    <a href="http://example.com?this=qux" class="baz_anchor">qux</a>
   </div>
  </td>
 </tr>
</table>
<script type="text/javascript" src="http://www.upstate.edu/assets/js/jquery-1.7.1.min.js"></script>
<script type="text/javascript" src="demo.js"></script>
</body>
</html>

My jQuery is below. I'm working with two anchors contained in separate TD elements which sort of look like they are on the same structural level, but are not actually DOM sibling nodes. It seems I can't use .closest() or .siblings() with this HTML and used a chain of .parent() and .children() instead. Is there a better way to do this?

link = $('a.baz_anchor:contains("baz")').parent().parent().parent().children().children('div#link1').children('a').attr('href');
alert(link);


Solution

  • A couple of shurtcuts can be taken here:

    1. Chain of parents can be substituted by single closest
    2. find looks through all layers of descendants, so a single selector can do for all children

    All in all:

    $('a.baz_anchor:contains("baz")').closest('tr')
                                     .find('div#link1 a')
                                     .attr('href')
    

    By the way, most of that is redundant if you really look up div by id, as in div#link1. Id is supposed to be unique on the page, so if this is really the case, all you need is just $('#link1 a').attr('href')