jqueryparent

Find element by class under the same parent


Any particular reason about this isn't matching the element with that class? I have checked a million times and can't see what is that I'm doing wrong.

$('.lnk-folder').click(function(e) {
  e.preventDefault();
  var header = $(this).parent('thead').find('.folder-header');
  console.log($(header));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<thead>
  <tr>
    <th colspan="10" style="padding:0px; font-size:120%;background-color:#ff0000;">
      <div style="float:left;min-width:20%;">
        <a style="color: #000" class="lnk-folder folder-close" data-hash="" href="#">
          <i class='fa fa-folder-open'></i> Folder 1
        </a>
      </div>
      <div style="float:left;height:26px;padding-left:10px;">
        <a href="#"><i class='fas fa-file-upload tooltip' style="color:#fff;"><span class="tooltiptext_m">New</span></i></a>
      </div>
    </th>
  </tr>
  <tr class="folder-header">
    <th colspan="2" style='background-color:#0c343d;vertical-align:middle;'> Name </th>
    <th style='width:7%;background-color:#0c343d;vertical-align:middle;'> Code </th>
    <th style='width:30%;background-color:#0c343d;vertical-align:middle;'> Act</th>
    <th style='width:7%;background-color:#0c343d;vertical-align:middle;'> Version</th>
  </tr>
</thead>


Solution

  • parent() is your problem. It looks up the DOM exactly one level, to the parent element, but you need to go higher than that. To do so, use closest()

    $('.lnk-folder').click(function(e) {
      e.preventDefault();
      var header = $(this).closest('thead').find('.folder-header');
      console.log($(header));
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <table>
      <thead>
        <tr>
          <th colspan="10" style="padding:0px; font-size:120%;background-color:#ff0000;">
            <div style="float:left;min-width:20%;">
              <a style="color: #000" class="lnk-folder folder-close" data-hash="" href="#">
                <i class='fa fa-folder-open'></i> Folder 1
              </a>
            </div>
            <div style="float:left;height:26px;padding-left:10px;">
              <a href="#"><i class='fas fa-file-upload tooltip' style="color:#fff;"><span class="tooltiptext_m">New</span></i></a>
            </div>
          </th>
        </tr>
        <tr class="folder-header">
          <th colspan="2" style='background-color:#0c343d;vertical-align:middle;'> Name </th>
          <th style='width:7%;background-color:#0c343d;vertical-align:middle;'> Code </th>
          <th style='width:30%;background-color:#0c343d;vertical-align:middle;'> Act</th>
          <th style='width:7%;background-color:#0c343d;vertical-align:middle;'> Version</th>
        </tr>
      </thead>
    </table>