Given the following table:
====|=====|=====|=====|
0 0 1 0
0 0 0 1
1 0 0 0
0 1 0 0
Tables in HTML are defined by rows and then columns. Thus the index of the elements selected with javascript also follow that order. So if I select all number '1's and put them in a loop. The first element selected will be the first '1' in the first row.
How would I go about selecting the first 1 in the first column, assuming that '1' can be anywhere in that column (one per column)? And then move to the second column and find the second number '1'?
Here's the loop that selects by rows:
//All '1's have a .one class
$("tr td.one").each(function(){});
============ UPDATE =============
@Alex Char answer is correct. I modified it a little so that it would work for what I am trying to achieve. He's how I ended up using his solution:
var all_ones = [];
$(".one").each(function(){
//Loop through all 1s get the td index and it's parent (tr) index.
all_ones.push([$(this).index(),$(this).parent().index()]);
});
//Sort all_ones by the td index
all_ones.sort(function(a, b) {
return a[0] - b[0];
});
//Loop throught the sorted index and print whatever
for(var i=0;i < all_ones.length;i++){
$("table tr:eq(" + all_ones[i][1] + ") td:eq(" + all_ones[i][0] + ")").css({color:"red"});
}
You can try to use .sort()* like:
var cells = $('table td').sort(function(a, b) {
//compare the cell index
var c0 = $(a).index();
var c1 = $(b).index();
if (c0 == c1) {
//compare the row index if needed
var r0 = $(a).parent().index();
var r1 = $(b).parent().index();
return r0 - r1;
} else
return c0 - c1;
});
//console.log(cells);
cells.each(function() {
if ($(this).html() == "1") {
$(this).css("background", "red");
}
document.write($(this).html());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td>0</td>
<td>0</td>
<td class="one">1</td>
<td>0</td>
</tr>
<tr>
<td>0</td>
<td>0</td>
<td>0</td>
<td class="one">1</td>
</tr>
<tr>
<td class="one">1</td>
<td>0</td>
<td>0</td>
<td>0</td>
</tr>
<tr>
<td>0</td>
<td class="one">1</td>
<td>0</td>
<td>0</td>
</tr>
</table>
*.sort() is not officially part of jquery.
References
.sort()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With