Generate a .row.cells row for every <tr> element's length

Greetings, I am interested in creating a script that can dynamically generate code based on the number of table rows it finds. Let me explain with an example:

Let's say I have a piece of code that calculates the number of table rows (excluding the table header) when I click a button:

var rowCount = $('#items-table tr').length - 1;

What I aim to achieve is, if the count I get is 3, I want to replicate these lines of code and update the variables and numbers within them accordingly.

Here are the initial lines of code I wish to duplicate:

table = document.getElementById("items-table");
var cell1 = table.rows[1].cells[0].innerHTML;
var cell2 = table.rows[1].cells[1].innerHTML;
var cell3 = table.rows[1].cells[2].innerHTML;

The goal is to modify the variable names so they can be defined later. For instance, if the count is 3, the output should look like this:

var cell1 = table.rows[1].cells[0].innerHTML;
var cell2 = table.rows[1].cells[1].innerHTML;
var cell3 = table.rows[1].cells[2].innerHTML;

var cell4 = table.rows[2].cells[0].innerHTML;
var cell5 = table.rows[2].cells[1].innerHTML;
var cell6 = table.rows[2].cells[2].innerHTML;

var cell7 = table.rows[3].cells[0].innerHTML;
var cell8 = table.rows[3].cells[1].innerHTML;
var cell9 = table.rows[3].cells[2].innerHTML;

How can I implement this? Furthermore, I would like to create a variable that can represent all the cell variables like this:

tableData = []   tableData.append(var cell7 = etc..)

This way, I could store the table data and retrieve it using localStorage in another HTML file. Additionally, I also intend to save the individual cell variables for future use:

localStorage.setItem("item-name-1", cell1);

Any suggestions on how I could accomplish this task are welcome. Thank you in advance.

Important Note: Initially, the table on my HTML page is empty. The data is then populated using inputs and an add button.

Answer №1

Utilize an array and a variable:

let table, cell, index, row, totalRows;
table = document.getElementById("items-table");
totalRows = table.rows.length;

for (index = 0, row = 0, cell = []; row < totalRows; index++, row++) {
  cell[index] = table.rows[row].cells[0].innerHTML;
  cell[index+1] = table.rows[row].cells[1].innerHTML;
  cell[index+2] = table.rows[row].cells[2].innerHTML;
}

Subsequently, the first cell will be stored in cell[0], the second in cell[1], and so on. For instance, document.write(cell[0]) will display "Item" (retrieved from your previous inquiry).

document.write(cell[1]) will show "Size".

document.write(cell[3]) will depict the initial cell of the second row.

Answer №2

You need to find an array, which in this case would likely be an array of arrays:

let cells = Array.prototype.map.call(document.getElementById("items-table").rows, row => {
    return Array.prototype.map.call(row.cells, cell => cell.innerHTML);
});

Check out this Live Example:

let cells = Array.prototype.map.call(document.getElementById("items-table").rows, row => {
    return Array.prototype.map.call(row.cells, cell => cell.innerHTML);
});
console.log("cells:", cells);
.as-console-wrapper {
  max-height: 100% !important;
}
<table id="items-table">
  <tbody>
    <tr>
      <td>Row 1 Cell 1</td>
      <td>Row 1 Cell 2</td>
      <td>Row 1 Cell 3</td>
    </tr>
    <tr>
      <td>Row 2 Cell 1</td>
      <td>Row 2 Cell 2</td>
      <td>Row 2 Cell 3</td>
    </tr>
    <tr>
      <td>Row 3 Cell 1</td>
      <td>Row 3 Cell 2</td>
      <td>Row 3 Cell 3</td>
    </tr>
    <tr>
      <td>Row 4 Cell 1</td>
      <td>Row 4 Cell 2</td>
      <td>Row 4 Cell 3</td>
    </tr>
  </tbody>
</table>

The part with Array.prototype.map.call enables us to use map function from Array on rows and cells, even though they are not arrays but have similar properties. Alternatively, you can convert them into arrays using Array.from:

let cells = Array.from(document.getElementById("items-table").rows).map(row => {
    return Array.from(row.cells).map(cell => cell.innerHTML);
});

Here is a Live Example:

let cells = Array.from(document.getElementById("items-table").rows).map(row => {
    return Array.from(row.cells).map(cell => cell.innerHTML);
});
console.log("cells:", cells);
.as-console-wrapper {
  max-height: 100% !important;
}
<table id="items-table">
  <tbody>
    <tr>
      <td>Row 1 Cell 1</td>
      <td>Row 1 Cell 2</td>
      <td>Row 1 Cell 3</td>
    </tr>
    <tr>
      <td>Row 2 Cell 1</td>
      <td>Row 2 Cell 2</td>
      <td>Row 2 Cell 3</td>
    </tr>
    <tr>
      <td>Row 3 Cell 1</td>
      <td>Row 3 Cell 2</td>
      <td>Row 3 Cell 3</td>
    </tr>
    <tr>
      <td>Row 4 Cell 1</td>
      <td>Row 4 Cell 2</td>
      <td>Row 4 Cell 3</td>
    </tr>
  </tbody>
</table>

To store this data in local storage, simply use JSON.stringify:

localStorage.setItem("tableData", JSON.stringify(cells));

For retrieval from local storage:

var cells = JSON.parse(localStorage.getItem("tableData") || "[]");

(The || "[]" adds a default empty array when there is no stored tableData.)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the reasoning behind using the IIFE pattern on certain straightforward member functions in three.js?

Consider the Object3D base class: rotateOnAxis: function () { // rotate object on axis in object space // axis is assumed to be normalized var q1 = new Quaternion(); return function rotateOnAxis( axis, angle ) { q1.setFromAxisA ...

Is there a way to preserve the HTML template code as it is when saving it in a cell?

Looking to store an HTML email template in a Google Sheet cell, but running into formatting issues. The code resembles this example: See sample Email HTML code The problem arises when pasting the complete email template HTML code in a cell. Upon copying ...

Ensure that the display is set to block to stack the input elements on top of each other

I am attempting to grasp the functionality of CSS display property and experimented with this basic HTML code: <div> <form className="container" action=""> <input name="fName" placeholder="First Name" type="text" value={props.fNam ...

Navigating the itemlist HTML to extract and manipulate data in a Flask application

In my current project, I am attempting to retrieve a value from an array in Flask based on the user's selection. Additionally, I need to perform calculations on this value within Flask as well. Below is the code snippet: HTML Code: <div class="f ...

The transparency effect on the overlaying image gradually diminishes as the images transition in the jQuery slideshow on Internet

My slideshow smoothly transitions between images, with a logo positioned to partly overlay it. Everything looks great except for one pesky issue in IE6 - when the images change, the part of the logo that overlaps the slideshow also fades. I don't wan ...

Conceal all columns apart from the first when expanding/collapsing a table using

I have a table with a single header and multiple columns, and I am trying to implement an expand/collapse feature based on header clicks using the code snippet below: $(this).toggleClass('expand').nextUntil('tr.header').slideToggle(100 ...

The browser is not showing JavaScript alerts and prompts when they are called inside a function

/*I am attempting to run a color guessing game in my browser, but when I try opening the code in Chrome, it doesn't work. Any suggestions or ideas would be greatly appreciated.*/ var colors = ["Aqua", "Black", "Blue", "Brown", "Coral", " ...

Executing asynchronous code in a sequential manner

I'm encountering a problem. I have an AngularJS function that calls another AngularJS function which includes a POST request. The issue is that this POST request always fires last, once the first function has completed. It doesn't execute sequent ...

What is the best way to eliminate the gap between the dropdown-toggle button and dropdown-menu items?

Why does a space appear between the dropdown-toggle button and dropdown-menu? Is there a way to remove this space? The box-shadow currently conceals the gap, but it becomes visible once the box-shadow is eliminated. Here is the code snippet: <!DOCT ...

Comprehension of async/await and the concept of promises

I am currently developing in node.js version 18.2.0 and here is the snippet of code I am working on: async function res_asyncf(){ await setTimeout(r => {}, 1000); } const res_promise = new Promise(async r => { await setTimeout(r, 1000); }); asyn ...

Can you provide tips on how to center the title on the page?

Currently, I am working on codepen.io and have been tasked with creating a paragraph that includes a title. However, my dilemma lies in the fact that I need this title to be center-aligned without directly altering the "x" value. Unfortunately, CSS is not ...

"Utilizing Express.js and PHP for Streamlined Functionality

I have been working on a project that involves using expressjs, Php, Html, and MongoDB. Here is the code snippet from my "Index.Html" File: <form action="/Login" method="POST"> <input type="text" placeholder="name" name="Username"> <in ...

The Battle: TypeScript versus JSX

After dabbling in TypeScript, I recently stumbled upon JSX and found them to be quite similar. However, when I tried to compare the two on this site, they only referenced Dart and other technologies, not TypeScript. Although both TypeScript and JSX compil ...

Eliminate the commas when listing Google Places types

I am currently utilizing the Google Places API and came across these code snippets at https://developers.google.com/maps/documentation/javascript/examples/place-search-pagination. var map, placesList; function initialize() { var pyrmont = new google.ma ...

What is preventing the mat-slide-toggle from being moved inside the form tags?

I've got a functioning slide toggle that works perfectly, except when I try to move it next to the form, it stops working. When placed within the form tag, the toggle fails to change on click and remains in a false state. I've checked out other ...

The animation does not seem to be functioning when applied to the input type button; however, it is

I've been attempting to apply animation to an input type button but haven't had any success yet. However, the animation works perfectly on a div tag and anchor tag. ...

How can I design a search box similar to the one on the android.com website?

Is it possible to replicate the search box effect on the Android website, where the menu items fade out and the search box expands upon clicking the search icon?view image here See the difference before and after clicking the search icon ...

Is it possible to link a css file from an ascx control during registration?

Is there a specific way to register a css code block within an ascx control? Do I simply place <head id="head" runat="server"> <style type="text/css"> .customClass { background-color: Lime; } < ...

Is there a way to display the next/previous buttons separately from the scroller in my jQuery thumbnail scroller implementation?

Is there a method to display the next and previous buttons outside of the scroller frame when using jQuery thumbnail scroller by manos.malihu.gr? I have attempted to modify the button class in CSS to make them more prominent or visible, but unfortunately ...

Is there a way to display a sub-menu while scrolling through a sub menu?

My dropdown menu is not displaying properly when there is a scroll bar on the page. I am using Bootstrap for my website. https://i.sstatic.net/tZFXh.png Below is the HTML code I am using: <a tabindex="-1" href="#">Location</a> ...