JavaScript get td from table [closed] - javascript

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I have a table with tbodies. I want to create a array with the values in the first td of with tbody. How can I do that?
My html:
<table id="myTable">
<thead>
<tr>
<th>Test1</th>
</tr>
</thead>
<tbody>
<tr>
<td>Val1</td>
<td></td>
<td></td>
</tr>
</tbody>
<tbody>
<tr>
<td>Val2</td>
<td></td>
<td></td>
</tr>
</tbody>
<tbody>
<tr>
<td>Val3</td>
<td></td>
<td></td>
</tr>
</tbody>
<tbody>
<tr>
<td>Val4</td>
<td></td>
<td></td>
</tr>
</tbody>
My array should have the values: Val1, Val2, Val3, Val4

There is a function called getElementsByTagName(tagName) which returns an array of elements.
Something like this should work:
var array = []; //your array
var rows = document.getElementById("myTable").getElementsByTagName("tr");
for(var i = 0; i < rows.length; i++) {
array[i] = rows[i].getElementsByTagName("td")[0].innerHTML;
}

Try this:
var bodies = document.getElementById("myTable").tBodies;
var items = [];
for (var i = 0; i < bodies.length; i++)
items.push(bodies[i].getElementsByTagName("td")[0].innerText);
alert(items);
<table id="myTable">
<thead>
<tr>
<th>Test1</th>
</tr>
</thead>
<tbody>
<tr>
<td>Val1</td>
<td></td>
<td></td>
</tr>
</tbody>
<tbody>
<tr>
<td>Val2</td>
<td></td>
<td></td>
</tr>
</tbody>
<tbody>
<tr>
<td>Val3</td>
<td></td>
<td></td>
</tr>
</tbody>
<tbody>
<tr>
<td>Val4</td>
<td></td>
<td></td>
</tr>
</tbody>

Try to use $(selector).map() at this context,
var x = $("#myTable > tbody > tr > td:first-child").map(function(){
return this.textContent;
}).get().join();
console.log(x); //Val1, Val2, Val3, Val4
DEMO
A pure javascript version by using Array.prototype.map() along with querySelectorAll(),
var x = [].map.bind(
document.querySelectorAll("#myTable > tbody > tr > td:first-child"),function(elem){
return elem.textContent;
})();
console.log(x); //Val1, Val2, Val3, Val4
DEMO

you can do this with jQuery:
var myArray=[];
$('#myTable tbody tr td:nth-child(1)').each(function(){
myArray.push($(this).text());
});

Just use the native javascript [Element].getElementsByTagName([TagName])[index] method.
// Get the array of <tbody> elements in the document.
tbodies = document.getElementsByTagName("tbody");
values = [];
// Loop through the array of <tbody> elements.
for(var index = 0; index < tbodies.length; index++) {
// Add the value of the <td> element to the array of values.
values += tbodies[index].firstChild.firstChild.nodeValue;
}
The line values += tbodies[index].firstChild.firstChild.nodeValue gets each <tbody> element and finds it's firstChild (the <tr> element) and finds the <tr> element's firstChild (the <td> element) and then finds the text that it contains (.nodeValue).
The values array ends up with resulting value of ["Val1","Val2","Val3","Val4"].

Related

How to replace <td> values in a table with jQuery (in every Rows)? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 months ago.
Improve this question
I have a table with multiple columns, one column named: ‘Type’. The values in Type column could be: 1 or 2.
I want to replace the value “1” to “Information” and the value “2” to “Problem” in every row with jQuery, how can I do that?
Here in this demo you'll find a function transformTableData() that takes the table existing in the document and will:
find where is located the field having as header the string "Type";
loop through all its rows and change the value of the corresponding field as the result coming out of the map defined on top. So according to the default map I defined, if the field value is '1' it will be transformed to 'Information' and if the value is '2' it will be transformed to 'Problem';
If there's no corresponding value in the map, the value will be untouched;
The function runs when you click the button on the bottom of the page. Of course the same function could be called on document ready.
function transformTableData(){
const map = {
'1' : 'Information',
'2' : 'Problem',
}
const typeHeaderCell = $('table thead tr th:contains(Type)');
const typeHeaderIndex = $(typeHeaderCell).index();
$('table tbody tr').each((i, row)=>{
const rowCell = $(row).find(`td:nth-child(${typeHeaderIndex+1})`);
const value = rowCell.text();
rowCell.text( map?.[value] );
});
}
table, tr, th, td{
border: solid 1px black;
padding: 1rem;
}
button{
margin-top: 1rem;
padding: 1rem;
font-size: 1.25rem;
cursor: pointer;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<thead>
<tr>
<th>Column1</th>
<th>Column2</th>
<th>...</th>
<th>Type</th>
<th>...</th>
<th>ColumnN</th>
</tr>
</thead>
<tbody>
<tr>
<td></td>
<td></td>
<td></td>
<td>1</td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td>2</td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td>INVALID</td>
<td></td>
<td></td>
</tr>
</tbody>
</table>
<button onclick="transformTableData();">Transform Table Data</button>
There are many ways to achieve something like this. Here is one example. It first looks for the index by comparing the text of each cell in the table header. then it gets all cells in the table body with the index in each table row and replaces the content if it is "1" or "2". There are for sure even shorter or faster methods.
// Find index of column with "Type"
let index = -1;
let th = $('#myTable thead tr th');
for (let i=0; i<th.length; i++) {
if ($(th[i]).text() == 'Type') {
index = i;
break;
}
}
// If index is greater then -1 we found the column
if (index > -1) {
// Get all the table cells in each row at the specific index (need to add +1 to the index)
let td = $('#myTable tbody tr td:nth-child(' + (index+1) + ')');
for (let i=0; i<td.length; i++) {
// Compare content and replace it
if ($(td[i]).text() == '1') {
$(td[i]).text('Information');
}
else if ($(td[i]).text() == '2') {
$(td[i]).text('Problem');
}
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="myTable">
<thead>
<tr>
<th>ID</th>
<th>Type</th>
<th>Name</th>
</tr>
</thead>
<tbody>
<tr>
<td>0</td>
<td>1</td>
<td>John</td>
</tr>
<tr>
<td>1</td>
<td>2</td>
<td>Maria</td>
</tr>
<tr>
<td>2</td>
<td>2</td>
<td>Walter</td>
</tr>
<tr>
<td>3</td>
<td>1</td>
<td>Julia</td>
</tr>
</tbody>
</table>

Javascript grab the data from the table in the HTML and build an array of objects that contains the table data

I have an HTML table and I need to define a function that should grab the data from the table and build an array of objects that contains table data. Outside the function I have to declare a variable and assign the returned value from the function.
Thanks in advance.
HTML
<table>
<thead>
<tr>
<th>Name</th>
<th>Rating</th>
<th>Review</th>
</tr>
</thead>
<tbody>
<tr>
<td>Bob</td>
<td>5/5</td>
<td>This product is so good, I bought 5 more!</td>
</tr>
<tr>
<td>Jane</td>
<td>4/5</td>
<td>Good value for the price.</td>
</tr>
<tr>
<td>David</td>
<td>1/5</td>
<td>Arrived broken :(</td>
</tr>
<tr>
<td>Fiona</td>
<td>5/5</td>
<td>I love it!</td>
</tr>
<tr>
<td>Michael</td>
<td>3/5</td>
<td>Doesn't live up to expectations.</td>
</tr>
</tbody>
</table>
JS
function buildTableData() {
let tbody = document.getElementsByTagName("tbody")[0];
let rows = tbody.children;
let people = [];
for (let row of rows) {
let person = {};
let cells = row.children;
person.rating = cells[0].textContent;
person.review = cells[1].textContent;
person.favoriteFood = cells[2].textContent;
people.push(person);
return people;
}
let data = people;
console.log(data);
}
You can get all the elements by using querySelectorAll('td'). Then use map to to get only the text of it and return this.
function buildTableData() {
const elements = [...document.querySelectorAll('td')];
return elements.map(x => {
return {content : x.innerHTML}
});
}
console.log(buildTableData());
<body>
<h2>Product reviews</h2>
<table>
<thead>
<tr>
<th>Name</th>
<th>Rating</th>
<th>Review</th>
</tr>
</thead>
<tbody>
<tr>
<td>Bob</td>
<td>5/5</td>
<td>This product is so good, I bought 5 more!</td>
</tr>
<tr>
<td>Jane</td>
<td>4/5</td>
<td>Good value for the price.</td>
</tr>
<tr>
<td>David</td>
<td>1/5</td>
<td>Arrived broken :(</td>
</tr>
<tr>
<td>Fiona</td>
<td>5/5</td>
<td>I love it!</td>
</tr>
<tr>
<td>Michael</td>
<td>3/5</td>
<td>Doesn't live up to expectations.</td>
</tr>
</tbody>
</table>
<script src="https://cdnjs.cloudflare.com/ajax/libs/acorn/7.3.1/acorn.js" integrity="sha512-4GRq4mhgV43mQBgKMBRG9GbneAGisNSqz6DSgiBYsYRTjq2ggGt29Dk5thHHJu38Er7wByX/EZoG+0OcxI5upg==" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/acorn-walk/7.2.0/walk.js" integrity="sha512-j5XDYQOKluxz1i4c7YMMXvjLLw38YFu12kKGYlr2+w/XZLV5Vg2R/VUbhN//K/V6LPKuoOA4pfcPXB5NgV7Gwg==" crossorigin="anonymous"></script>
<script src="index.js"></script>
</body>
You can try using querySelectorAll() and map() like the following way:
function buildTableData() {
let rows = document.querySelectorAll('tbody tr');
let data = Array.from(rows).map(function(tr){
return {
rating: tr.querySelectorAll('td:nth-child(1)')[0].textContent,
review: tr.querySelectorAll('td:nth-child(2)')[0].textContent,
favoriteFood: tr.querySelectorAll('td:nth-child(3)')[0].textContent
};
});
console.log(data);
}
buildTableData();
<h2>Product reviews</h2>
<table>
<thead>
<tr>
<th>Name</th>
<th>Rating</th>
<th>Review</th>
</tr>
</thead>
<tbody>
<tr>
<td>Bob</td>
<td>5/5</td>
<td>This product is so good, I bought 5 more!</td>
</tr>
<tr>
<td>Jane</td>
<td>4/5</td>
<td>Good value for the price.</td>
</tr>
<tr>
<td>David</td>
<td>1/5</td>
<td>Arrived broken :(</td>
</tr>
<tr>
<td>Fiona</td>
<td>5/5</td>
<td>I love it!</td>
</tr>
<tr>
<td>Michael</td>
<td>3/5</td>
<td>Doesn't live up to expectations.</td>
</tr>
</tbody>
</table>
You want a loop, and each review to be an object that is appended to an array of reviews is what I'm assuming
var reviews = [];
var tbody = document.querySelectorAll("tbody")[0];
var TRs = tbody.querySelectorAll("tr");
for (var a = 0; a < TRs.length; a++) {
var TDs = TRs[a].querySelectorAll("td");
var review = {
name: "",
rating: "",
review: ""
};
//These assume the order of your table columns don't change
review.name = TDs[0].innerHTML;
review.rating = TDs[1].innerHTML;
review.review = TDs[2].innerHTML;
reviews.push(review);
}
Your reviews array should have everything in there just as you wanted. I assumed the third column was "review" instead of "favorite food"

Reverse table rows top row go on bottom without change the position of th, HOW?

I use the HTML code.
I have a table and I write in first tr td "A" and "B" in second tr td
I have these two rows
but I want to print "B" in first tr and "A" in second
!! But I don't want to change my th position!!
Is it possible with any script like js or Jquery or with any type js CDN....??
<table id='table1'>
<tr>
<th>name</th>
</tr>
<tr>
<td>A</td>
</tr>
<tr>
<td>B</td>
</tr>
</table>
Give this a try:
Your script
$(function(){
$("tbody").each(function(elem,index){
var arr = $.makeArray($("tr",this).detach());
arr.reverse();
$(this).append(arr);
});
});
The second way to do the same will be like this:
var tbody = $('table tbody');
tbody.html($('tr',tbody).get().reverse());
I hope this helps! Thanks!
You can swap the .textContent of the <td> children of the <tr> elements
const {rows:[{cells:[a]}, {cells:[b]}]} = table1;
[a.textContent, b.textContent] = [b.textContent, a.textContent];
<table id='table1'>
<tr>
<td>A</td>
</tr>
<tr>
<td>B</td>
</tr>
</table>
Since you can use reverse() with an array, you can use get() to convert this to an array first. If you have a dynamic number of rows you can use something like this:
$('tbody').each(function(){
var row = $(this).children('tr');
console.log(row)
$(this).html(row.get().reverse())
})
Use this below code:
$(function(){
$("tbody").each(function(elem,index){
var arr = $.makeArray($("tr",this).detach());
arr.reverse();
$(this).append(arr);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id='table1'>
<tbody>
<tr>
<td>A</td>
</tr>
<tr>
<td>B</td>
</tr>
<tr>
<td>C</td>
</tr>
</tbody>
</table>
You can loop through each row, starting at the bottom and add it to the bottom - this will reverse the rows.
This will mean you don't need to load all the rows into an array, but will mean additional DOM manipulation.
var tbl = $("#table1>tbody")
var l = tbl.find("tr").length;
for (var i=l; i>=0; --i)
{
tbl.find("tr").eq(i).appendTo(tbl);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id='table1'><tbody>
<tr> <td>A</td> </tr>
<tr> <td>B</td> </tr>
<tr> <td>C</td> </tr>
<tr> <td>D</td> </tr>
<tr> <td>E</td> </tr>
</tbody></table>
Problem Solved
<script type="text/javascript">
var trCount = $('#table1 tr').length;
var $rows = [];
for (var i = 0; i < trCount; i++)
$rows.push($('#table1 tr:last-child').remove());
$("#table1 tbody").append($rows);
</script>
Thanks to all
You can do that with pure vanilla JS, you don't need jquery or any other library for that.
function reverseOrder(table) {
const rows = table.querySelector('tbody').children;
const swaptemp = rows[0].children[0].innerHTML;
rows[0].children[0].innerHTML = rows[1].children[0].innerHTML;
rows[1].children[0].innerHTML = swaptemp;
}
const tableToReserveOrder = document.getElementById('table1');
reverseOrder(tableToReserveOrder);
<table id='table1'>
<tr>
<td>A</td>
</tr>
<tr>
<td>B</td>
</tr>
</table>
This is just a demonstration for your use case, you can play around with value of n which is 0 for this case where n+1 is 1.

jQuery - Create an array from a 2-column table

I have a 2-column table and I would like to convert the cells into an array using jQuery. I currently have that working, but I would like the array to be "2-column" as well, not sure if that's the right terminology. But basically I want the 2 cells from each row to be part of the same "row" in the array. Currently I have this:
$(function() {
var arr = [];
$('tbody tr').each(function() {
var $this = $(this),
cell = $this.find('td');
if (cell.length > 0) {
cell.each(function() {
arr.push($(this).text());
});
}
});
console.log(arr);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<thead>
<tr>
<td>Table heading</td>
</tr>
</thead>
<tbody>
<tr>
<td>Apples</td>
<td>Red</td>
</tr>
<tr>
<td>Bananas</td>
<td>Yellow</td>
</tr>
<tr>
<td>Oranges</td>
<td>Orange</td>
</tr>
<tr>
<td>Cucumbers</td>
<td>Green</td>
</tr>
</table>
How do I make it so that 0 would be Apples, Red and so on?
You can do something like this
$(function() {
var arr = $('tbody tr').get()//convert jquery object to array
.map(function(row) {
return $(row).find('td').get()
.map(function(cell) {
return cell.innerHTML;
}).join(',');
});
console.log(arr);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<thead>
<tr>
<td>Table heading</td>
</tr>
</thead>
<tbody>
<tr>
<td>Apples</td>
<td>Red</td>
</tr>
<tr>
<td>Bananas</td>
<td>Yellow</td>
</tr>
<tr>
<td>Oranges</td>
<td>Orange</td>
</tr>
<tr>
<td>Cucumbers</td>
<td>Green</td>
</tr>
</table>
ok you can also do this.
$(function() {
var arr = [];
flag = 0;
$('tbody tr td').each(function() {
if(flag == 0){
arr1 = [];
arr1.push($(this).text());
arr.push(arr1);
flag = 1;
}else{
let arr1 = arr[arr.length-1];
arr1.push($(this).text());
arr[arr.length-1] = arr1;
flag = 0;
}
});
console.log(arr);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<thead>
<tr>
<td>Table heading</td>
</tr>
</thead>
<tbody>
<tr>
<td>Apples</td>
<td>Red</td>
</tr>
<tr>
<td>Bananas</td>
<td>Yellow</td>
</tr>
<tr>
<td>Oranges</td>
<td>Orange</td>
</tr>
<tr>
<td>Cucumbers</td>
<td>Green</td>
</tr>
</table>
I'd suggest:
// using Array.from() to convert the Array-like NodeList returned
// from document.querySelectorAll() into an Array, in order to use
// Array.prototype.map():
let array = Array.from(document.querySelectorAll('tbody tr')).map(
// tr: a reference to the current array-element of the Array over
// which we're iterating; using Arrow function syntax:
(tr) => {
// here we return the result of the following expression;
// again using Array.from() to convert the NodeList of
// the <tr> element's children into an Array, again in order
// to utilise Array.prototype.map():
return Array.from(tr.children).map(
// cell is a reference to the current Node of the Array
// of Nodes over which we're iterating; here we implicitly
// return the textContent of each <td> ('cell') Node; after
// using String.prototype.trim() to remove leading/trailing
// white-space:
(cell) => cell.textContent.trim()
);
});
let array = Array.from(document.querySelectorAll('tbody tr')).map(
(tr) => {
return Array.from(tr.children).map(
(cell) => cell.textContent.trim()
);
});
console.log(array);
<table>
<thead>
<tr>
<td>Table heading</td>
</tr>
</thead>
<tbody>
<tr>
<td>Apples</td>
<td>Red</td>
</tr>
<tr>
<td>Bananas</td>
<td>Yellow</td>
</tr>
<tr>
<td>Oranges</td>
<td>Orange</td>
</tr>
<tr>
<td>Cucumbers</td>
<td>Green</td>
</tr>
</table>
References:
Array.from().
Array.prototype.map().
Arrow functions.
document.querySelectorAll().
ParentNode.children.
String.prototype.trim().

Sorting pairs of rows with tablesorter

http://jsfiddle.net/9sKwJ/66/
tr.spacer { height: 40px; }
$.tablesorter.addWidget({
id: 'spacer',
format: function(table) {
var c = table.config,
$t = $(table),
$r = $t.find('tbody').find('tr'),
i, l, last, col, rows, spacers = [];
if (c.sortList && c.sortList[0]) {
$t.find('tr.spacer').removeClass('spacer');
col = c.sortList[0][0]; // first sorted column
rows = table.config.cache.normalized;
last = rows[0][col]; // text from first row
l = rows.length;
for (i=0; i < l; i++) {
// if text from row doesn't match last row,
// save it to add a spacer
if (rows[i][col] !== last) {
spacers.push(i-1);
last = rows[i][col];
}
}
// add spacer class to the appropriate rows
for (i=0; i<spacers.length; i++){
$r.eq(spacers[i]).addClass('spacer');
}
}
}
});
$('table').tablesorter({
widgets : ['spacer']
});
<table id="test">
<thead>
<tr>
<th>Name</th>
<th>Number</th>
<th>Another Example</th>
</tr>
</thead>
<tbody>
<tr>
<td>Test4</td>
<td>4</td>
<td>Hello4</td>
</tr>
<tr>
<td colspan="3">Test4</td>
</tr>
<tr>
<td>Test3</td>
<td>3</td>
<td>Hello3</td>
</tr>
<tr>
<td colspan="3">Test3</td>
</tr>
<tr>
<td>Test2</td>
<td>2</td>
<td>Hello2</td>
</tr>
<tr>
<td colspan="3">Test2</td>
</tr>
<tr>
<td>Test1</td>
<td>1</td>
<td>Hello1</td>
</tr>
<tr>
<td colspan="3">Test1</td>
</tr>
</tbody>
</table>
This sorts just the way I want it if you sort it by the first column, but the other two columns don't maintain the same paired 'tr' sort im looking for.
Any help on this?
Use the expand-child class name on each duplicated row:
<tr>
<td>Test3</td>
<td>3</td>
<td>Hello3</td>
</tr>
<tr class="expand-child">
<td colspan="3">Test3</td>
</tr>
It's defined by the cssChildRow option:
$('table').tablesorter({
cssChildRow: "expand-child"
});​
Here is a demo of it in action.

Categories

Resources