I need to sort the first td elements of 3 tables. I must use jQuery to do it not pure javascript. Example:
<table>
<tr>
<td>cx</td>
<td>xx</td>
</tr>
</table>
<table>
<tr>
<td>bx</td>
<td>xx</td>
</tr>
</table>
<table>
<tr>
<td>ax</td>
<td>xx</td>
</tr>
</table>
The result I would like to get is:
<table>
<tr>
<td>ax</td>
<td>xx</td>
</tr>
</table>
<table>
<tr>
<td>bx</td>
<td>xx</td>
</tr>
</table>
<table>
<tr>
<td>cx</td>
<td>xx</td>
</tr>
</table>
Edit 1: that is what I'm trying to do: if you just could tell me how to get the current td element value it would be nice for me
Edit 2: Now The values in the result is the same as before sorting. Sorry for my mistake
var table = $("table");
var currentTableTd;
$.each(table, function(k, v) {
//currentTableTd = v.find("td:first-child");
//window.console.log(currentTableTd); // will log error v.find() is not a function which I understand because var v isn't a Jquery object.
//or
currentTableTd = $(this).find("td:first-child").text();
window.console.log(currentTableTd); //log undefined
})
you could use sort, then replace the html:-
var sorted = $('table').sort(function(a, b) {
return $('td:first', a).text().localeCompare($('td:first', b).text());
}).clone();
sorted.each(function(i, e) {
$('table').eq(i).html($(e).html());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td>cx</td>
<td>xx</td>
</tr>
</table>
<table>
<tr>
<td>bx</td>
<td>xx</td>
</tr>
</table>
<table>
<tr>
<td>ax</td>
<td>xx</td>
</tr>
</table>
Finally after working on this problem during 24hours I have found my own solution. I post it here. Maybe it could helps other people.
Special thanks to those people who "voted down" on my question without helping me. They gave me the willpower to find my own solution.
var table = $("table");
$.each(table, function (k, v) {
var $currentTable = $("table").eq(k);
var $tr = $currentTable.find("tr").not(":first");
var $tdAll = $tr.find("td:first");
var textNodes = []; //collecting textNodes of td elements
var map = {}; //mapping $tdAll
var result = []; //contains sorted td elements to be added to the dom
$.each($tdAll, function (k, v) {
textNodes.push($(v).text());
map[k] = $(v);
})
textNodes.sort();
for (var i = 0; i < textNodes.length; i++) {
for (var key in map) {
if (textNodes[i] === $(map[key]).text())
result.push($(map[key]));
}
}
//Dom construction
$tr.find("td").remove();
for (var i = 0; i < textNodes.length; i++) {
$tr.eq(i).find("td:first").before($(result[i]));
}
})
Related
I have multiple tables in a dOM tree and I want to calculate the count of cells in every table.
code:
function tree() {
var table = document.getElementsByTagName('table');
for (var p = 0, tr; tr= table[p]; p++) {
for (var i =0, row; row = tr.rows[i]; i++) {
console.log(row.cells.length)
}
}
}
console.log(tree())
html:
<table>
<tr>
<td>First</td>
<td>row</td>
</tr>
<tr>
<td>and</td>
<td>second</td>
</tr>
</table>
<table>
<tr>
<td>First</td>
<td>row</td>
</tr>
</table>
In the first there are 4 cells and second there are 2 cells I want to print out the cells with largest count in a table. Hence the o/p will be:
4
my above js code, returns the total length of all the cells in a table. How can I traverse through the tables in a tree and find the largest count of cells?
thx!
Use querySelectorAll() to simplify this.
The below code will output 4 as in your OP. It's a simple modification to get the table with the most cells, which I suspect is what you meant (it's unclear).
// Get your list of all tables in the document.
const tables = document.querySelectorAll('table');
// Map list of tables to list of number of <td> elements.
const lengths =
Array.from(tables)
.map(table => table.querySelectorAll('td').length)
// Get the max of the list of lengths and log to console.
const max = Math.max(...lengths);
console.log(max);
<table>
<tr>
<td>First</td>
<td>row</td>
</tr>
<tr>
<td>and</td>
<td>second</td>
</tr>
</table>
<table>
<tr>
<td>First</td>
<td>row</td>
</tr>
</table>
You can try this to if you want :
const maxTdTable = ()=>{
var object;
var maxCol = 0;
$('table').each(function(element){
$(element).each(function(elem){
max = $(elem).childNodes.length;
maxCol = max>=maxCol ? max : maxCol ;
});
});
return {element : object,max : maxCol};
}
I have an HTML table and I want to iterate through its rows and create a collection or lets say an "array of objects".
For example:
<table id="tbPermission">
<tr>
<th>User ID</th>
<th>User Name</th>
</tr>
<tr>
<td>1</td>
<td>Test1</td>
</tr>
</table>
I want to create a collection as below:
var trArray = [];
$('#tbPermission tr').each(function () {
var tdArray = [];
$(this).find('td').each(function () {
// I want to create the array of objects here …
tdArray.push();
});
// Final array
trArray.push(tdArray);
});
The arrays may be like below:
tdArray : {'UserID' : '1', 'UserName' : 'Test1'};
and:
trArray : [
{'UserID' : '1', 'UserName' : 'Test1'},
{'UserID' : '2', 'UserName' : 'Test2'}
]
Try this code
var trArray = [];
$('#tbPermission tr').each(function () {
var tr =$(this).text(); //get current tr's text
var tdArray = [];
$(this).find('td').each(function () {
var td = $(this).text(); //get current td's text
var items = {}; //create an empty object
items[tr] = td; // add elements to object
tdArray.push(items); //push the object to array
});
});
Here, I just created an empty object, filled object with references of tr and td, the added that object to the final array.
adding a working jsfiddle
This solution relies on adding thead and tbody elements which is a good idea anyways since it indicates to the browser that the table actually is a "data" table and not presentational.
jQuery has a .map() function. map is a basic function where you take an array and then replace the values with a the return value of a callback function - which results in a new array.
$([1,4,9]).map(function(){ return Math.sqrt(this) });
// [1, 2, 3]
.toArray converts the array like jQuery object we get into a "true array".
jQuery(function(){
var $table = $("#tbPermission");
var headers = $table.find('thead th').map(function(){
return $(this).text().replace(' ', '');
});
var rows = $table.find('tbody tr').map(function(){
var result = {};
var values = $(this).find('>td').map(function(){
return $(this).text();
});
// use the headers for keys and td values for values
for (var i = 0; i < headers.length; i++) {
result[headers[i]] = values[i];
}
// If you are using Underscore/Lodash you could replace this with
// return _.object(headers, values);
return result;
}).toArray();
// just for demo purposes
$('#test').text(JSON.stringify(rows));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="tbPermission">
<thead>
<tr>
<th>User ID</th>
<th>User Name</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>Test1</td>
</tr>
</tbody>
</table>
<textarea id="test"></textarea>
If you for whatever reason cannot change the HTML you could use the index of the rows to differentiate between headers and rows of data:
var headers = $table.find('tr:eq(0) th').map(function(){
return $(this).text().replace(' ', '');
});
var rows = $table.find('tr:gt(0)').map(function(){
// ...
});
I would suggest changing your html slightly.
<table id="tbPermission">
<tr>
<th>User ID</th>
<th>User Name</th>
</tr>
<tr>
<td class="userid">1</td>
<td class="username">Test1</td>
</tr>
</table>
Then in your javascript when you want to get all the elements as an array you could do.
var userIdArray = $('#tbPermission .userid').map(function(userid){ return $(userid).html(); }).toArray();
This will find all elements with a class userid on the table, collect just the values, and .toArray() that result to get a basic javascript array. You can then take that and manipulate it into whatever json structure you want, or you could possibly create your json object inside that map function.
Check the console, you will get an array with the desired objects
var arr = [];
$('#tbPermission tr:not(.header)').each(function() {
var that = $(this);
var id = that.find('td').eq(0).text();
var name = that.find('td').eq(1).text();
var obj = { 'userId': id , 'userName': name };
arr.push(obj);
});
console.log(arr);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table id="tbPermission">
<tr class="header">
<th>User ID</th>
<th>User Name</th>
</tr>
<tr>
<td>1</td>
<td>Test1</td>
</tr>
<tr>
<td>2</td>
<td>Test2</td>
</tr>
</table>
It's a bit tricky based on the given structure. You may have to modify the HTML a bit to map cells to headers, like below.
var myArray = [];
$("#tbPermission").find("td").each(function() {
var $this = $(this), obj = {};
obj[$this.data("column")] = $this.text();
myArray.push(obj);
});
alert ( JSON.stringify(myArray) );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="tbPermission">
<tr>
<th>User ID</th>
<th>User Name</th>
</tr>
<tr>
<td data-column="User ID">1</td>
<td data-column="User Name">Test1</td>
</tr>
</table>
Please give in some time to learn about Array.push() and Objects in Javascript. Hope that helps.
I'm a beginner with code,
I'm trying to run on this table and get the text from each .winner class and push it to an Array, so instead of getting:
["aa","aa","dd"]
I'm getting
["aaaadd","aaaadd","aaaadd"]
$(document).ready(function(){
var arr = [];
var winner = $('.winner').text() ;
for ( i = 0; i < $('table').length ; i++ ) {
arr.push(winner);
}
console.log(arr);
});
HTML:
<table>
<tr>
<td>#</td>
<td class="winner">aa</td>
<td>bb</td>
<td>cc</td>
<td>dd</td>
</tr>
</table>
<table>
<tr>
<td>#</td>
<td class="winner">aa</td>
<td>bb</td>
<td>cc</td>
<td>dd</td>
</tr>
</table>
<table>
<tr>
<td>#</td>
<td class="winner">dd</td>
<td>cc</td>
<td>bb</td>
<td>aa</td>
</tr>
</table>
I guess something is wrong with my for loop
var arr = [];
$('table .winner').each(function () {
arr.push($(this).text());
})
Example
or version without class .winner
$('table').each(function () {
arr.push($(this).find('tr').eq(0).find('td').eq(1).text());
});
Example
$('table .winner') - returns 3 td's with class .winner
$(this).text() - get text from current element.
In your example $('.winner').text() returns text "aaaadd", then you get $('table').length (will be 3) and three times push the same text to arr
The sentence
var winner = $('.winner')
will give you an array of objects, so you need to loop each of them and call text() method for each one.
With this:
var winner = $('.winner').text();
You are getting a combined texts from all the td elements marked as winner (see docs here).
Then, for each table, to push this value to the array:
for ( i = 0; i < $('table').length ; i++ ) {
arr.push(winner);
}
This is actually not necessary.
What you want is probably:
var winners = $('.winner');
for (var i = 0; i < winners.length(); ++i) {
arr.push(winners.eq(i).text());
}
If I have an HTML table...say
<div id="myTabDiv">
<table name="mytab" id="mytab1">
<tr>
<td>col1 Val1</td>
<td>col2 Val2</td>
</tr>
<tr>
<td>col1 Val3</td>
<td>col2 Val4</td>
</tr>
</table>
</div>
How would I iterate through all table rows (assuming the number of rows could change each time I check) and retrieve values from each cell in each row from within JavaScript?
If you want to go through each row(<tr>), knowing/identifying the row(<tr>), and iterate through each column(<td>) of each row(<tr>), then this is the way to go.
var table = document.getElementById("mytab1");
for (var i = 0, row; row = table.rows[i]; i++) {
//iterate through rows
//rows would be accessed using the "row" variable assigned in the for loop
for (var j = 0, col; col = row.cells[j]; j++) {
//iterate through columns
//columns would be accessed using the "col" variable assigned in the for loop
}
}
If you just want to go through the cells(<td>), ignoring which row you're on, then this is the way to go.
var table = document.getElementById("mytab1");
for (var i = 0, cell; cell = table.cells[i]; i++) {
//iterate through cells
//cells would be accessed using the "cell" variable assigned in the for loop
}
You can consider using jQuery. With jQuery it's super-easy and might look like this:
$('#mytab1 tr').each(function(){
$(this).find('td').each(function(){
//do your stuff, you can use $(this) to get current cell
})
})
Try
for (let row of mytab1.rows)
{
for(let cell of row.cells)
{
let val = cell.innerText; // your code below
}
}
for (let row of mytab1.rows)
{
for(let cell of row.cells)
{
console.log(cell.innerText)
}
}
<div id="myTabDiv">
<table name="mytab" id="mytab1">
<tr>
<td>col1 Val1</td>
<td>col2 Val2</td>
</tr>
<tr>
<td>col1 Val3</td>
<td>col2 Val4</td>
</tr>
</table>
</div>
for ( let [i,row] of [...mytab1.rows].entries() )
{
for( let [j,cell] of [...row.cells].entries() )
{
console.log(`[${i},${j}] = ${cell.innerText}`)
}
}
<div id="myTabDiv">
<table name="mytab" id="mytab1">
<tr>
<td>col1 Val1</td>
<td>col2 Val2</td>
</tr>
<tr>
<td>col1 Val3</td>
<td>col2 Val4</td>
</tr>
</table>
</div>
var table=document.getElementById("mytab1");
var r=0; //start counting rows in table
while(row=table.rows[r++])
{
var c=0; //start counting columns in row
while(cell=row.cells[c++])
{
cell.innerHTML='[R'+r+'C'+c+']'; // do sth with cell
}
}
<table id="mytab1">
<tr>
<td>A1</td><td>A2</td><td>A3</td>
</tr>
<tr>
<td>B1</td><td>B2</td><td>B3</td>
</tr>
<tr>
<td>C1</td><td>C2</td><td>C3</td>
</tr>
</table>
In each pass through while loop r/c iterator increases and new row/cell object from collection is assigned to row/cell variables. When there's no more rows/cells in collection, false is assigned to row/cell variable and iteration through while loop stops (exits).
Better solution: use Javascript's native Array.from() and to convert HTMLCollection object to an array, after which you can use standard array functions.
var t = document.getElementById('mytab1');
if(t) {
Array.from(t.rows).forEach((tr, row_ind) => {
Array.from(tr.cells).forEach((cell, col_ind) => {
console.log('Value at row/col [' + row_ind + ',' + col_ind + '] = ' + cell.textContent);
});
});
}
You could also reference tr.rowIndex and cell.colIndex instead of using row_ind and col_ind.
I much prefer this approach over the top 2 highest-voted answers because it does not clutter your code with global variables i, j, row and col, and therefore it delivers clean, modular code that will not have any side effects (or raise lint / compiler warnings)... without other libraries (e.g. jquery). Furthermore, it gives your code access to both element and index vars rather than just the element, and if you prefer to hide the index, you can just ignore it in the callback arg list.
If you require this to run in an old version (pre-ES2015) of Javascript, Array.from can be polyfilled.
If you want one with a functional style, like this:
const table = document.getElementById("mytab1");
const cells = table.rows.toArray()
.flatMap(row => row.cells.toArray())
.map(cell => cell.innerHTML); //["col1 Val1", "col2 Val2", "col1 Val3", "col2 Val4"]
You may modify the prototype object of HTMLCollection (allowing to use in a way that resembles extension methods in C#) and embed into it a function that converts collection into array, allowing to use higher order funcions with the above style (kind of linq style in C#):
Object.defineProperty(HTMLCollection.prototype, "toArray", {
value: function toArray() {
return Array.prototype.slice.call(this, 0);
},
writable: true,
configurable: true
});
Here's one solution using modern Javascript ES6+
const rows = document.querySelector("table")?.rows;
if (!rows) {
return;
}
Array.from(rows).forEach(row => {
console.log(row);
const cells = Array.from(row.cells);
cells.forEach(cell => {
console.log(cell);
});
});
Array.from() converts the HTMLCollection of rows and/or cells into a regular Javascript Array which you can iterate through.
Documentation for table.rows usage: https://developer.mozilla.org/en-US/docs/Web/API/HTMLTableElement/rows
Documentation for row.cells usage: https://developer.mozilla.org/en-US/docs/Web/API/HTMLTableRowElement
This solution worked perfectly for me
var table = document.getElementById("myTable").rows;
var y;
for(i = 0; i < # of rows; i++)
{ for(j = 0; j < # of columns; j++)
{
y = table[i].cells;
//do something with cells in a row
y[j].innerHTML = "";
}
}
You can use .querySelectorAll() to select all td elements, then loop over these with .forEach(). Their values can be retrieved with .innerHTML:
const cells = document.querySelectorAll('td');
cells.forEach(function(cell) {
console.log(cell.innerHTML);
})
<table name="mytab" id="mytab1">
<tr>
<td>col1 Val1</td>
<td>col2 Val2</td>
</tr>
<tr>
<td>col1 Val3</td>
<td>col2 Val4</td>
</tr>
</table>
If you want to only select columns from a specific row, you can make use of the pseudo-class :nth-child() to select a specific tr, optionally in conjunction with the child combinator (>) (which can be useful if you have a table within a table):
const cells = document.querySelectorAll('tr:nth-child(2) > td');
cells.forEach(function(cell) {
console.log(cell.innerHTML);
})
<table name="mytab" id="mytab1">
<tr>
<td>col1 Val1</td>
<td>col2 Val2</td>
</tr>
<tr>
<td>col1 Val3</td>
<td>col2 Val4</td>
</tr>
</table>
My solution, using es6:
var table = document.getElementById('mytab1');
var data = [...table.rows].map(row => [...row.cells].map(td => td.innerText));
console.log(data)
REFERENCES:
https://developer.mozilla.org/pt-BR/docs/Web/API/HTMLCollection
Using a single for loop:
var table = document.getElementById('tableID');
var count = table.rows.length;
for(var i=0; i<count; i++) {
console.log(table.rows[i]);
}
I leave this just for future reference for scraping a specific HTML table column and printing the results.
//select what table you want to scrape (is zero based)
//set 0 if there is only one
setTable=0;
//select what column you want to scrape (is zero based)
//in this case I would be scrapping column 2
setColumnToScrape=1;
var table = document.getElementsByTagName("tbody")[setTable];
for (var i = 0, row; row = table.rows[i]; i++) {
col = row.cells[setColumnToScrape];
document.write(col.innerHTML + "<br>");
}
This is a different method using the childNodes and HTMLCollection
<script>
var tab = document.getElementsByTagName("table")
for (var val of tab[0].childNodes[1].childNodes.values())
if (HTMLCollection.prototype.isPrototypeOf(val.children)) {
for (var i of val.children) {
console.log(i.childNodes[0])
}
}
</script>
Pure Javascript
function numberofRow(){
var x = document.getElementById("mytab1").rows.length;
document.getElementById("mytab1").innerHTML = x;
}
numberofRow();
<div id="myTabDiv">
<table name="mytab" id="mytab1">
<tr>
<td>col1 Val1</td>
<td>col2 Val2</td>
</tr>
<tr>
<td>col1 Val3</td>
<td>col2 Val4</td>
</tr>
</table>
</div>
es6:
const table = document.getElementById('some-table');
const cells = table.getElementsByTagName('td');
for (let cell of cells) {
// do something with cell here
}
earlier versions:
var table = document.getElementById('some-table');
var cells = table.getElementsByTagName('td');
for ( var i in cells ) {
// do something with cells[i]
}
source: https://developer.mozilla.org/en-US/docs/Web/API/Element/getElementsByTagName
If I have an HTML table...say
<div id="myTabDiv">
<table name="mytab" id="mytab1">
<tr>
<td>col1 Val1</td>
<td>col2 Val2</td>
</tr>
<tr>
<td>col1 Val3</td>
<td>col2 Val4</td>
</tr>
</table>
</div>
How would I iterate through all table rows (assuming the number of rows could change each time I check) and retrieve values from each cell in each row from within JavaScript?
If you want to go through each row(<tr>), knowing/identifying the row(<tr>), and iterate through each column(<td>) of each row(<tr>), then this is the way to go.
var table = document.getElementById("mytab1");
for (var i = 0, row; row = table.rows[i]; i++) {
//iterate through rows
//rows would be accessed using the "row" variable assigned in the for loop
for (var j = 0, col; col = row.cells[j]; j++) {
//iterate through columns
//columns would be accessed using the "col" variable assigned in the for loop
}
}
If you just want to go through the cells(<td>), ignoring which row you're on, then this is the way to go.
var table = document.getElementById("mytab1");
for (var i = 0, cell; cell = table.cells[i]; i++) {
//iterate through cells
//cells would be accessed using the "cell" variable assigned in the for loop
}
You can consider using jQuery. With jQuery it's super-easy and might look like this:
$('#mytab1 tr').each(function(){
$(this).find('td').each(function(){
//do your stuff, you can use $(this) to get current cell
})
})
Try
for (let row of mytab1.rows)
{
for(let cell of row.cells)
{
let val = cell.innerText; // your code below
}
}
for (let row of mytab1.rows)
{
for(let cell of row.cells)
{
console.log(cell.innerText)
}
}
<div id="myTabDiv">
<table name="mytab" id="mytab1">
<tr>
<td>col1 Val1</td>
<td>col2 Val2</td>
</tr>
<tr>
<td>col1 Val3</td>
<td>col2 Val4</td>
</tr>
</table>
</div>
for ( let [i,row] of [...mytab1.rows].entries() )
{
for( let [j,cell] of [...row.cells].entries() )
{
console.log(`[${i},${j}] = ${cell.innerText}`)
}
}
<div id="myTabDiv">
<table name="mytab" id="mytab1">
<tr>
<td>col1 Val1</td>
<td>col2 Val2</td>
</tr>
<tr>
<td>col1 Val3</td>
<td>col2 Val4</td>
</tr>
</table>
</div>
var table=document.getElementById("mytab1");
var r=0; //start counting rows in table
while(row=table.rows[r++])
{
var c=0; //start counting columns in row
while(cell=row.cells[c++])
{
cell.innerHTML='[R'+r+'C'+c+']'; // do sth with cell
}
}
<table id="mytab1">
<tr>
<td>A1</td><td>A2</td><td>A3</td>
</tr>
<tr>
<td>B1</td><td>B2</td><td>B3</td>
</tr>
<tr>
<td>C1</td><td>C2</td><td>C3</td>
</tr>
</table>
In each pass through while loop r/c iterator increases and new row/cell object from collection is assigned to row/cell variables. When there's no more rows/cells in collection, false is assigned to row/cell variable and iteration through while loop stops (exits).
Better solution: use Javascript's native Array.from() and to convert HTMLCollection object to an array, after which you can use standard array functions.
var t = document.getElementById('mytab1');
if(t) {
Array.from(t.rows).forEach((tr, row_ind) => {
Array.from(tr.cells).forEach((cell, col_ind) => {
console.log('Value at row/col [' + row_ind + ',' + col_ind + '] = ' + cell.textContent);
});
});
}
You could also reference tr.rowIndex and cell.colIndex instead of using row_ind and col_ind.
I much prefer this approach over the top 2 highest-voted answers because it does not clutter your code with global variables i, j, row and col, and therefore it delivers clean, modular code that will not have any side effects (or raise lint / compiler warnings)... without other libraries (e.g. jquery). Furthermore, it gives your code access to both element and index vars rather than just the element, and if you prefer to hide the index, you can just ignore it in the callback arg list.
If you require this to run in an old version (pre-ES2015) of Javascript, Array.from can be polyfilled.
If you want one with a functional style, like this:
const table = document.getElementById("mytab1");
const cells = table.rows.toArray()
.flatMap(row => row.cells.toArray())
.map(cell => cell.innerHTML); //["col1 Val1", "col2 Val2", "col1 Val3", "col2 Val4"]
You may modify the prototype object of HTMLCollection (allowing to use in a way that resembles extension methods in C#) and embed into it a function that converts collection into array, allowing to use higher order funcions with the above style (kind of linq style in C#):
Object.defineProperty(HTMLCollection.prototype, "toArray", {
value: function toArray() {
return Array.prototype.slice.call(this, 0);
},
writable: true,
configurable: true
});
Here's one solution using modern Javascript ES6+
const rows = document.querySelector("table")?.rows;
if (!rows) {
return;
}
Array.from(rows).forEach(row => {
console.log(row);
const cells = Array.from(row.cells);
cells.forEach(cell => {
console.log(cell);
});
});
Array.from() converts the HTMLCollection of rows and/or cells into a regular Javascript Array which you can iterate through.
Documentation for table.rows usage: https://developer.mozilla.org/en-US/docs/Web/API/HTMLTableElement/rows
Documentation for row.cells usage: https://developer.mozilla.org/en-US/docs/Web/API/HTMLTableRowElement
This solution worked perfectly for me
var table = document.getElementById("myTable").rows;
var y;
for(i = 0; i < # of rows; i++)
{ for(j = 0; j < # of columns; j++)
{
y = table[i].cells;
//do something with cells in a row
y[j].innerHTML = "";
}
}
You can use .querySelectorAll() to select all td elements, then loop over these with .forEach(). Their values can be retrieved with .innerHTML:
const cells = document.querySelectorAll('td');
cells.forEach(function(cell) {
console.log(cell.innerHTML);
})
<table name="mytab" id="mytab1">
<tr>
<td>col1 Val1</td>
<td>col2 Val2</td>
</tr>
<tr>
<td>col1 Val3</td>
<td>col2 Val4</td>
</tr>
</table>
If you want to only select columns from a specific row, you can make use of the pseudo-class :nth-child() to select a specific tr, optionally in conjunction with the child combinator (>) (which can be useful if you have a table within a table):
const cells = document.querySelectorAll('tr:nth-child(2) > td');
cells.forEach(function(cell) {
console.log(cell.innerHTML);
})
<table name="mytab" id="mytab1">
<tr>
<td>col1 Val1</td>
<td>col2 Val2</td>
</tr>
<tr>
<td>col1 Val3</td>
<td>col2 Val4</td>
</tr>
</table>
My solution, using es6:
var table = document.getElementById('mytab1');
var data = [...table.rows].map(row => [...row.cells].map(td => td.innerText));
console.log(data)
REFERENCES:
https://developer.mozilla.org/pt-BR/docs/Web/API/HTMLCollection
Using a single for loop:
var table = document.getElementById('tableID');
var count = table.rows.length;
for(var i=0; i<count; i++) {
console.log(table.rows[i]);
}
I leave this just for future reference for scraping a specific HTML table column and printing the results.
//select what table you want to scrape (is zero based)
//set 0 if there is only one
setTable=0;
//select what column you want to scrape (is zero based)
//in this case I would be scrapping column 2
setColumnToScrape=1;
var table = document.getElementsByTagName("tbody")[setTable];
for (var i = 0, row; row = table.rows[i]; i++) {
col = row.cells[setColumnToScrape];
document.write(col.innerHTML + "<br>");
}
This is a different method using the childNodes and HTMLCollection
<script>
var tab = document.getElementsByTagName("table")
for (var val of tab[0].childNodes[1].childNodes.values())
if (HTMLCollection.prototype.isPrototypeOf(val.children)) {
for (var i of val.children) {
console.log(i.childNodes[0])
}
}
</script>
Pure Javascript
function numberofRow(){
var x = document.getElementById("mytab1").rows.length;
document.getElementById("mytab1").innerHTML = x;
}
numberofRow();
<div id="myTabDiv">
<table name="mytab" id="mytab1">
<tr>
<td>col1 Val1</td>
<td>col2 Val2</td>
</tr>
<tr>
<td>col1 Val3</td>
<td>col2 Val4</td>
</tr>
</table>
</div>
es6:
const table = document.getElementById('some-table');
const cells = table.getElementsByTagName('td');
for (let cell of cells) {
// do something with cell here
}
earlier versions:
var table = document.getElementById('some-table');
var cells = table.getElementsByTagName('td');
for ( var i in cells ) {
// do something with cells[i]
}
source: https://developer.mozilla.org/en-US/docs/Web/API/Element/getElementsByTagName