Search code examples
javascriptjquerydomtraversal

jQuery traversal - finding previous label to current input


Just a quick question as I haven't been using jQuery for that long.

Is there a neater/quicker way to get to the html for a label in this scenario.

Here is a dumbed down version as an example,

<tr>
   <td>
       <label>Please fill in name:</label>
   </td>
   <td>
       <input type="text" id="txtName" class="validate" />
   </td>
</tr>
<tr>
   <td>
       <label>Date of Birth:</label>
   </td>
   <td>
       <input type="text" id="txtDOB" class="validate" />
   </td>
</tr>

This is the jquery snippet i'm using currently to grab the html for the labels.

$(document).ready(function(){
   $('.validate').each(function(){
      if(!$(this).val())
      {
          var label = $(this).parent().prev().find('label').html();
          alert(label);
      }
   }); 
});

Any ideas are appreciated


Solution

  • yes, there is another neat way to do so by using Closest() instead of Parent()

    Consider the following code:

    $(document).ready(function(){
       $('.validate').each(function(){
          if(!$(this).val())
          {
              var label = $(this).closest("tr").find('label').html();
              alert(label);
          }
       }); 
    });
    

    Closest(): Get the first element that matches the selector, beginning at the current element and progressing up through the DOM tree.