I am not able to select certain range of td
for the whole table in jquery.
Or what is the same, I am looking to paint/capture all the cells of all the rows except the cells of the last column, but I don't know why it only works with the first row.
I say jquery because I think it's the fastest, but if someone knows how to do it in ES without getting complicated, that's even better.
$(document).ready(function(){
$('tr td:lt(2)').css("background-color", "yellow");
$("table").on('click','tr td:lt(2)', function() {
console.log(this)
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table border="1">
<tr>
<td>Alfreds Futterkiste</td>
<td>Maria Anders</td>
<td>Germany</td>
</tr>
<tr>
<td>Berglunds snabbköp</td>
<td>Christina Berglund</td>
<td>Sweden</td>
</tr>
<tr>
<td>Centro comercial Moctezuma</td>
<td>Francisco Chang</td>
<td>Mexico</td>
</tr>
<tr>
<td>Ernst Handel</td>
<td>Roland Mendel</td>
<td>Austria</td>
</tr>
<tr>
<td>Island Trading</td>
<td>Helen Bennett</td>
<td>UK</td>
</tr>
<tr>
<td>Königlich Essen</td>
<td>Philip Cramer</td>
<td>Germany</td>
</tr>
<tr>
<td>Laughing Bacchus Winecellars</td>
<td>Yoshi Tannamuri</td>
<td>Canada</td>
</tr>
<tr>
<td>Magazzini Alimentari Riuniti</td>
<td>Giovanni Rovelli</td>
<td>Italy</td>
</tr>
<tr>
<td>North/South</td>
<td>Simon Crowther</td>
<td>UK</td>
</tr>
</table>
Your solution
$('tr td:lt(2)').css("background-color", "yellow");
doesn't work because you are selecting only cells(td
) that have an index less than2
. Since you have 3 cells, it only paints the first 2 (indexes 0 and 1).To select the range of cells you say you can use the following selector.
table tr:not(:last-child) td
: selects all the elementstd
of all the rows (tr
) and that the row is not the last (:not(:last-child)
).with jquery
vanilla javascript (pure)
I have finally found the solution with the
find
jquery method and also with the pure css selectorsI have realized that when it is done
tr td:gt(1):lt(3)
, it does it on the table and not for each tr, which is what I was looking for. In the first two example tables it is clearly seen.To finally solve it with
$('#tabla tr').find('td:gt(1):lt(3)')
I have even with pure css selectors that I suppose will be valid for pure javascript$('#tabla td:nth-child(n+3):nth-child(-n+5)')