How to get the column index of a specific td value in HTML tables

Hi,

I created an HTML table and I need to find the column index of a specific value, but I donโ€™t know how to access each value of the table. That is why I cannot get the column index.

Here is my table.

<table> <tr> <td>01</td> <td>02</td> <td>03</td> </tr> <tr> <td>04</td> <td>05</td> <td>06</td> </tr> <tr> <td>07</td> <td>08</td> <td>09</td> </tr> </table> 

and I want a value index of 03.

+4
source share
3 answers

Below is the working code, first cross the table to get the values โ€‹โ€‹in this, then compare with your required value and find its index ..,

  <html> <head> <script> function cellvalues() { var table = document.getElementById('mytable'); for (var r = 0, n = table.rows.length; r < n; r++) { for (var c = 0, m = table.rows[r].cells.length; c < m; c++) { var hi=table.rows[r].cells[c].innerHTML; if(hi==03) { alert(table.rows[r].cells[c].cellIndex); } } } } </script> </head> <body> <table id="mytable"> <tr><td>01</td><td>02</td><td>03</td> </tr> <tr><td>04</td><td>05</td><td>06</td> </tr> <tr><td>07</td><td>08</td><td>09</td> </tr> </table> <input type="button" onclick=cellvalues()> </body> </html> 
0
source

You can try this one (untested)

 var tab = document.getElementsByTagName("table")[0]; var tr = tab.childNodes; for (var i = 0; i < tr.length; i++) { var td = tr[i].childNodes; for (var j = 0; j < tr.length; j++) { if (td[j].innerHTML == "03") { alert(i + "," + j); } } } 
0
source

I suggest using the jQuery index for this:

 var trCollection = $('table tr'); $('table td').each(function () { console.log(trCollection.index($(this).parent())); }); 
-one
source

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


All Articles