Find the value of the table header cell (first column)

I have an HTML table referenced at http://jsfiddle.net/Lijo/sP7zD/ . I need to read the header value of the first columns. I do this with the gt and lt operators. But it does not get the value of the first column.

  • What jQuery code change needs to be done in the script I wrote?
  • What is the best way to read the header value of the first columns?

CODE

<input type="submit" value="Alert" class="alertButton"/> <table class="resultGridTable" cellspacing="0" id="detailContentPlaceholder_grdLocalTaxReport" style="border-collapse: collapse;"> <tr> <th scope="col"> IsSummaryRow </th> <th scope="col"> Associate </th> <th scope="col"> Gross Amount </th> <th scope="col"> Federal Withholding </th> </tr> <tr> <td> False </td> <td> Norman Tylor </td> <td> 3450 </td> <td> 32 </td> </tr> </table> <script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jquery/jquery-1.4.1.js"></script> 

SCRIPT

 $('.alertButton').click(function() { var selectedElements = $("tr").find("th:gt(0):lt(1)"); $(selectedElements).css('background-color','yellow'); alert(selectedElements.html()); }); 

+4
source share
4 answers

Use $('th:first')

 var selectedElements = $("th:first"); 

Here is a demo .

For your code: use eq instead.

 var selectedElements = $("tr").find("th:eq(0)"); 
+3
source

To answer question 1, your code is trying to find an element with an index greater than 0, so it finds the second. Try to remove gt . This will find the element with index less than 1, so it will match the element with index 0.

 var selectedElements = $("tr").find("th:lt(1)"); 

But there are better ways to do this, as mentioned in other answers.

+1
source

try it

HTML code

 <input type="submit" value="Alert" class="alertButton" /> <table class="resultGridTable" cellspacing="0" id="detailContentPlaceholder_grdLocalTaxReport" style="border-collapse: collapse;"> <tr> <th scope="col"> IsSummaryRow </th> <th scope="col"> Associate </th> <th scope="col"> Gross Amount </th> <th scope="col"> Federal Withholding </th> </tr> <tr> <td> False </td> <td> Norman Tylor </td> <td> 3450 </td> <td> 32 </td> </tr> </table> <script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jquery/jquery-1.4.1.js"> </script> 

Js code

 $('.alertButton').click(function() { var selectedElements = $('th').first(); alert(selectedElements .text()); selectedElements.css({'background':'yellow'}); }); 

Demo

+1
source

Use var selectedElements = $(".resultGridTable").find("tr:first").find('th:first');

 $('.alertButton').click(function() { var selectedElements = $(".resultGridTable").find("tr:first").find('th:first'); $(selectedElements).css('background-color','yellow'); alert(selectedElements.html()); }); 

0
source

Source: https://habr.com/ru/post/1434999/


All Articles