I have a HTML table as listed in http://jsfiddle.net/Lijo/sP7zD/ . I need to read the value of first column's header. I am doing it with “gt” and “lt” operators. But it is not getting the first column value.
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());
});
Use $('th:first')
var selectedElements = $("th:first");
For your code: change to use eq
instead.
var selectedElements = $("tr").find("th:eq(0)");
To answer question 1, your code tries to find the element with an index greater than 0, so it finds the second. Try removing the gt
. This will find the element with an index less than 1, so it will match the element with an index of 0.
var selectedElements = $("tr").find("th:lt(1)");
But there are better ways of doing this, as mentioned in other answers.
Try this
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'});
});
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());
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.