A user clicks on a row of a table, and I want to get (in Javascript) the innerhtml of let's say the 3rd column of that row.
Something like :
document.getElementById("tblBlah").rows[i].columns[j].innerHTML
doesn't seem achievable and I can't find anything here or in the net.
Any solutions would be very much appreciated ( NO jQuery )
You can use the Core/index function in a given context, for example you can check the index of the TD in it's parent TR to get the column number, and you can check the TR index on the Table, to get the row number: $('td'). click(function(){ var col = $(this). parent().
To count the number of rows, the “#Table_Id tr” selector is used. It selects all the <tr> elements in the table. This includes the row that contains the heading of the table. The length property is used on the selected elements to get the number of rows.
document.getElementById("tblBlah").rows[i].columns[j].innerHTML;
Should be:
document.getElementById("tblBlah").rows[i].cells[j].innerHTML;
But I get the distinct impression that the row/cell you need is the one clicked by the user. If so, the simplest way to achieve this would be attaching an event to the cells in your table:
function alertInnerHTML(e)
{
e = e || window.event;//IE
alert(this.innerHTML);
}
var theTbl = document.getElementById('tblBlah');
for(var i=0;i<theTbl.length;i++)
{
for(var j=0;j<theTbl.rows[i].cells.length;j++)
{
theTbl.rows[i].cells[j].onclick = alertInnerHTML;
}
}
That makes all table cells clickable, and alert it's innerHTML. The event object will be passed to the alertInnerHTML
function, in which the this
object will be a reference to the cell that was clicked. The event object offers you tons of neat tricks on how you want the click event to behave if, say, there's a link in the cell that was clicked, but I suggest checking the MDN and MSDN (for the window.event object)
in case if your table has tbody
let tbl = document.getElementById("tbl").getElementsByTagName('tbody')[0];
console.log(tbl.rows[0].cells[0].innerHTML)
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