I have the following code to get the headers from my table but after some searching I didn't find a clear way to do it for the columns. Can someone help me do a similar function to extract columns from my table? (without the header). Thanks in advance guys
The code i have for headers:
var header = [];
$('.theader ').each(function(index, item) {
header[index] = $(item).html();
});
You could do something like this using vanilla javascript
let columnData = Array.from(table.rows).
slice(1, table.rows.length).
map(row =>Array.from(row.cells).map(x => x.innerText)).
reduce((acc,rowData)=>{
rowData.forEach((value,index)=>{
acc[index]= acc[index] || [ ]
acc[index].push(value)
})
return acc },[])
let table = document.getElementById('tab')
debugger
let headers = Array.from(table.rows[0].cells).map(x => x.innerText)
let columnData =
Array.from(table.rows).
slice(1, table.rows.length).
map(row =>Array.from(row.cells).map(x => x.innerText))
.reduce((acc,rowData)=>{
rowData.forEach((value,index)=>{
acc[index]= acc[index] || [ ]
acc[index].push(value) })
return acc },[])
console.log(headers)
console.log(columnData)
<table id="tab">
<tr>
<th>
Name
</th>
<th>
Age
</th>
<th>
Location
</th>
</tr>
<tr>
<th>
Jason
</th>
<th>
22
</th>
<th>
Texas
</th>
</tr>
<tr>
<th>
Lawson
</th>
<th>
21
</th>
<th>
Florida
</th>
</tr>
<tr>
<th>
Jose
</th>
<th>
25
</th>
<th>
London
</th>
</tr>
</table>