Reputation: 304
I have table with images with 4 cols and 2 rows. I shuffle the table using this code:
function sortTable() {
//get the parent table for convenience
let table = document.getElementById("imgTable");
//1. get all rows
let rowsCollection = table.querySelectorAll("td");
//2. convert to array
let rows = Array.from(rowsCollection)
//3. shuffle
shuffleArray(rows);
//4. add back to the DOM
for (const row of rows) {
table.appendChild(row);
}
}
function shuffleArray(array) {
for (var i = array.length - 1; i > 0; i--) {
var j = Math.floor(Math.random() * (i + 1));
var temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
But after shuffle, everything gets into 1 row and 8 cols. How do i keep the dimension same?
Here is the Demo of what is happening
Upvotes: 2
Views: 65
Reputation: 23406
Like said in the comment, you're appending the shuffled cells directly to the table element. That's not a permitted parent element for td
elements. Instead, distribute the shuffled cells back to the original rows.
function sortTable() {
//get the parent table for convenience
let table = document.getElementById("imgTable");
//1. get all rows
let cellCollection = table.querySelectorAll("td");
//2. convert to array
let cells = Array.from(cellCollection)
//3. shuffle
shuffleArray(cells);
//4. add back to the DOM
const rows = table.rows,
len = rows.length;
let index = 0;
for (const cell of cells) {
const row = rows[index++ % len];
row.appendChild(cell);
}
}
function shuffleArray(array) {
for (var i = array.length - 1; i > 0; i--) {
var j = Math.floor(Math.random() * (i + 1));
var temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
sortTable();
<table id="imgTable">
<tr>
<td>R1C1</td>
<td>R1C2</td>
<td>R1C3</td>
<td>R1C4</td>
</tr>
<tr>
<td>R2C1</td>
<td>R2C2</td>
<td>R2C3</td>
<td>R2C4</td>
</tr>
</table>
I've also changed some variable names to better describe the content.
Upvotes: 1
Reputation: 1255
I think you select wrong selector it should be tr
function sortTable() {
//get the parent table for convenience
let table = document.getElementById("imgTable");
//1. get all rows
let rowsCollection = table.querySelectorAll("tr");
//2. convert to array
let rows = Array.from(rowsCollection)
//3. shuffle
shuffleArray(rows);
//4. add back to the DOM
for (const row of rows) {
table.appendChild(row);
}
}
function shuffleArray(array) {
for (var i = array.length - 1; i > 0; i--) {
var j = Math.floor(Math.random() * (i + 1));
var temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
const shuffle = document.getElementById('shuffle');
shuffle.addEventListener('click', () => {
sortTable()
});
<button id="shuffle">shuffle</button>
<table id="imgTable">
<tr>
<td>1</td>
<td>1</td>
<td>1</td>
<td>1</td>
</tr>
<tr>
<td>2</td>
<td>2</td>
<td>2</td>
<td>2</td>
</tr>
<tr>
<td>3</td>
<td>3</td>
<td>3</td>
<td>3</td>
</tr>
</table>
Upvotes: 2