Reputation: 8096
I am trying to figure out how to select a column in a table based on the table heading. What I have figured out, with lots of googling, so far is this:
<html>
<body>
<table>
<tr><th class='x29'>A</th><th class='x29'>B</th><th class='x29'>C</th><th class='x29'>D</th></tr>
<tr><td>1</td><td>2</td><td>3</td><td>4</td></tr>
<tr><td>5</td><td>6</td><td>7</td><td>8</td></tr>
<tr><td>9</td><td>10</td><td>11</td><td>12</td></tr>
</table>
<script>
$(document).ready(function() {
var l_col;
$('th.x29').each(function () {
if ($(this).text() == 'C') {
l_col = $(this).index();
$(this).closest('tr').next().children().eq(l_col+1).append("<b>A String</b>");
}
});
});
</script>
</body>
</html>
Unfortunately this only appends "A String" to the first row of the column for which the heading is "C". How can I append "A String" to the entire column for which the heading is "C". Better code than mine would be appreciated.
Upvotes: 2
Views: 1073
Reputation: 195992
How about
$(document).ready(function () {
var l_col = $('th.x29').filter(function(){
return $(this).text() === 'C';
}).index() +1 ;
$('tr td:nth-child(' + l_col + ')').append('<b>A String</b>');
});
Demo at http://jsfiddle.net/HfjLa/
Upvotes: 0
Reputation: 30993
You can get the nth cell of every row by using a combination of contains
, index
and nth:child
selector.
Code:
$(document).ready(function () {
$("tr td:nth-child(" + ($('th.x29:contains("C")').index()+1) + ")").append("<b>A String</b>")
});
Demo: http://jsfiddle.net/IrvinDominin/VWr7X/
Upvotes: 1