Skip to content
Advertisement

How can I get the name of the class of the td element in the same row of a table using attribute, from javascript [closed]

I am trying to get the name of the classname assigned to the td element in an html table. I have given the class name for two tds and rest of the tds without class name. If I click checkbox element, I want to get the class name of that tds having data-pk=”NormalHrs” attribute only in the same row,

Here is the code

<script>
    $("input:checkbox").on('click', function () {
                 var $box = $(this);
                var classname =   $box.parent('td').closest('td.data-pk="NormalHrs"').classname  

    })
</script>
   <td class="EditableTd"><a href="#" data-pk="NormalHrs" class="editable editable-click">0.00</a><input type="hidden" class="bros" data-val="true" data-val-number="The field NormalHrs must be a number." data-val-required="The NormalHrs field is required." id="attendanceLogList_0__NormalHrs" name="attendanceLogList[0].NormalHrs" value="0.00"></td>

 

<td class="holidaycheck"><input type="checkbox" value="true" data-tag="HolidayHrs" data-val="true" data-val-required="The IsHolidayMarked field is required." id="attendanceLogList_0__IsHolidayMarked" name="attendanceLogList[0].IsHolidayMarked" autocomplete="off"><input type="hidden" value="false" id="attendanceLogList_0__IsHolidayMarked" name="attendanceLogList[0].IsHolidayMarked"> </td>

strong text Any help would be appreciated

Advertisement

Answer

Assuming you only know the cell has something with data-pk=”NormalHrs” and you need its className, try this

$("input:checkbox").on('click', function() {
  const className = $(this).closest('tr').find("[data-pk=NormalHrs]").closest("td").attr("class")
  console.log(className)
})

// OR

$("input:checkbox").on('click', function() {
  const className = $(this).closest('tr').find('td:has(".editable")').attr("class")
  console.log(className)
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
  <tr>
    <td class="EditableTd">
      <a href="#" data-pk="NormalHrs" class="editable editable-click">0.00</a>
      <input type="hidden" class="bros" data-val="true" data-val-number="The field NormalHrs must be a number." data-val-required="The NormalHrs field is required." id="attendanceLogList_0__NormalHrs" name="attendanceLogList[0].NormalHrs" value="0.00">
    </td>
    <td class="holidaycheck">
      <input type="checkbox" value="true" data-tag="HolidayHrs" data-val="true" data-val-required="The IsHolidayMarked field is required." id="attendanceLogList_0__IsHolidayMarked" name="attendanceLogList[0].IsHolidayMarked" autocomplete="off">
      <input type="hidden" value="false" id="attendanceLogList_0__IsHolidayMarked" name="attendanceLogList[0].IsHolidayMarked"> </td>
  </tr>
</table>
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement