0

I have a table in HTML, which has 616 rows. However, I would like to add an extra column, and each of the rows for that column would contain the same element. Is there a way with JS to do that? What I would like to add on each row for that column is this symbol Which is just an add button that goes in every element. Here is my code:

<div class="scrollingTable">
  <div class="row justify-content-center">
    <div class="col-md-8 col-lg-8 mb-8">
      <input type="text" id="myInput" onkeyup="myFunction()" placeholder="Search for names.." title="Type in a name">
      <table id="myTable" cellspacing="0" cellpadding="1" border="1" width="300">
        <thead>
          <tr>
            <th title="Field #1">drinkName</th>
            <th title="Field #2">drinkSizeInFlOz</th>
            <th title="Field #3">calories</th>
            <th title="Field #4">caffeineInMg</th>
            <th title="Field #5">caffeineInMgPerFloz</th>
            <th title="Field #6">type</th>
          </tr>
        </thead>
        <tbody>
          <tr>
            <td>28 Black Energy Drink</td>
            <td>8.46</td>
            <td align="right">125</td>
            <td align="right">80</td>
            <td align="right">9.5</td>
            <td>ED</td>
            <td><button type="submit" id="myButton">+</button></td>
          </tr>
          <tr>
            <td>3 Water </td>
            <td>16.9</td>
            <td align="right">0</td>
            <td align="right">50</td>
            <td align="right">3.0</td>
            <td>W</td>
            <td><button type="submit" id="myButton">+</button></td>
          </tr>
          <tr>
            <td>3D Energy Drink</td>
            <td>16</td>
            <td align="right">15</td>
            <td align="right">200</td>
            <td align="right">12.5</td>
            <td>ED</td>
            <td><button type="submit" id="myButton">+</button></td>
          </tr>
          <tr>
            <td>4 Purpose Energy Drink</td>
            <td>8.46</td>
            <td align="right">70</td>
            <td align="right">70</td>
            <td align="right">8.3</td>
            <td>ED</td>
            <td><button type="submit" id="myButton">+</button></td>
          </tr>
          <tr>
            <td>4C Energy Drink Mix</td>
            <td>16.9</td>
            <td align="right">15</td>
            <td align="right">170</td>
            <td align="right">10.1</td>
            <td>ED</td>
            <td><button type="submit" id="myButton">+</button></td>
          </tr>
          <tr>
            <td>5 Hour Energy</td>
            <td>1.93</td>
            <td align="right">4</td>
            <td align="right">200</td>
            <td align="right">103.6</td>
            <td>ES</td>
            <td><button type="submit" id="myButton">+</button></td>
          </tr>
          <tr>
            <td>5 Hour Energy Extra Strength</td>
            <td>1.93</td>
            <td align="right">0</td>
            <td align="right">230</td>
            <td align="right">119.2</td>
            <td>ES</td>
            <td><button type="submit" id="myButton">+</button></td>
          </tr>
          <tr>

1
  • For a button to be added, you will need to loop and insert the element[s] into the DOM. There is no quick solution. Commented Jun 21, 2022 at 12:17

4 Answers 4

1

I created the jsfiddle for your problem.

var trs = document.querySelectorAll("#myTable tbody tr");
for (var tr of trs) {
  let td = document.createElement("td");
  let btn = document.createElement("button");
  btn.innerHTML = "+";
  btn.type = "submit";
  td.appendChild(btn);
  tr.appendChild(td);
}
<html>
<body>
<div class="scrollingTable">
                <div class="row justify-content-center">
                    <div class="col-md-8 col-lg-8 mb-8" >
                        <input type="text" id="myInput" onkeyup="myFunction()" placeholder="Search for names.." title="Type in a name" >
                        <table id="myTable" cellspacing="0" cellpadding="1" border="1" width="300">
                            <thead>
                                <tr>
                                    <th title="Field #1">drinkName</th>
                                    <th title="Field #2">drinkSizeInFlOz</th>
                                    <th title="Field #3">calories</th>
                                    <th title="Field #4">caffeineInMg</th>
                                    <th title="Field #5">caffeineInMgPerFloz</th>
                                    <th title="Field #6">type</th>
                                </tr>
                            </thead>
                            <tbody>
                                <tr>
                                    <td>28 Black Energy Drink</td>
                                    <td>8.46</td>
                                    <td align="right">125</td>
                                    <td align="right">80</td>
                                    <td align="right">9.5</td>
                                    <td>ED</td>
                                </tr>
                                <tr>
                                    <td>3 Water </td>
                                    <td>16.9</td>
                                    <td align="right">0</td>
                                    <td align="right">50</td>
                                    <td align="right">3.0</td>
                                    <td>W</td>
                                </tr>
                                <tr>
                                    <td>3D Energy Drink</td>
                                    <td>16</td>
                                    <td align="right">15</td>
                                    <td align="right">200</td>
                                    <td align="right">12.5</td>
                                    <td>ED</td>
                                </tr>
                                <tr>
                                    <td>4 Purpose Energy Drink</td>
                                    <td>8.46</td>
                                    <td align="right">70</td>
                                    <td align="right">70</td>
                                    <td align="right">8.3</td>
                                    <td>ED</td>
                                </tr>
                                <tr>
                                    <td>4C Energy Drink Mix</td>
                                    <td>16.9</td>
                                    <td align="right">15</td>
                                    <td align="right">170</td>
                                    <td align="right">10.1</td>
                                    <td>ED</td>
                                </tr>
                                <tr>
                                    <td>5 Hour Energy</td>
                                    <td>1.93</td>
                                    <td align="right">4</td>
                                    <td align="right">200</td>
                                    <td align="right">103.6</td>
                                    <td>ES</td>
                                </tr>
                                <tr>
                                    <td>5 Hour Energy Extra Strength</td>
                                    <td>1.93</td>
                                    <td align="right">0</td>
                                    <td align="right">230</td>
                                    <td align="right">119.2</td>
                                    <td>ES</td>
                                </tr>
                                
                                </tbody>
                                </table>
                                </div>
                                </div>
                                </div>
                                
</body>
</html>

Sign up to request clarification or add additional context in comments.

1 Comment

with a sufficient explaination this could have been a good answer. As of now it is a code only answer whcih is hard to understand. (unelss of course you know the solution, in whcihc ase you wouldnt need to ask in the first place).
0

There are a lot of ways to insert a column into each row of a table. It all depends on what libraries you are using. I will assume that you are using vanilla Javascript, (i.e: no external libraries).

Here is one way to insert a column, and control the content of each cell, including detecting if you are currently on the table header, or normal cell.

const btn = document.getElementById('my-button');
btn.addEventListener('click', function(){
  const tr = document.querySelectorAll('#my-table tr');
  tr.forEach((row,index) => {
    let cell;
    if(index===0) {
      cell = document.createElement('th');
      cell.innerText = "fourth column";
    } else {
      cell = document.createElement('td');
      cell.innerText = `row ${index},4`;
    }
    
    row.appendChild(cell);
  });
  
});
table, td, th
{
border: 1px solid grey;
border-collapse: collapse;
}

td, th
{
padding: 1em;
}

button
{
margin-top: 2em;
}
<button id="my-button">Insert missing column</button>

<table id="my-table">
  <thead>
    <tr>
      <th>first column</th>
      <th>second column</th>
      <th>third column</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>row 1, 1</td>
      <td>row 1, 2</td>
      <td>row 1, 3</td>
    </tr>
    <tr>
      <td>row 2, 1</td>
      <td>row 2, 2</td>
      <td>row 2, 3</td>
    </tr>
    <tr>
      <td>row 3, 1</td>
      <td>row 3, 2</td>
      <td>row 3, 3</td>
    </tr>
  </tbody>
</table>

Comments

0

const rows = document.getElementsByTagName("table")[0].rows; //Get all rows

for (let i = 1; i < rows.length; i++) { // Iterate rows of body
  const row = rows[i]; // Get row
  const button = document.createElement("button"); // Create button
  button.innerHTML = "+"; // Set text of button
  const cell = document.createElement("td"); // Create column
  cell.appendChild(button); // Add button to column
  row.appendChild(cell); // Add column to row
}
<div class="scrollingTable">
  <div class="row justify-content-center">
    <div class="col-md-8 col-lg-8 mb-8">
      <input type="text" id="myInput" onkeyup="myFunction()" placeholder="Search for names.." title="Type in a name">
      <table id="myTable" cellspacing="0" cellpadding="1" border="1" width="300">
        <thead>
          <tr>
            <th title="Field #1">drinkName</th>
            <th title="Field #2">drinkSizeInFlOz</th>
            <th title="Field #3">calories</th>
            <th title="Field #4">caffeineInMg</th>
            <th title="Field #5">caffeineInMgPerFloz</th>
            <th title="Field #6">type</th>
          </tr>
        </thead>
        <tbody>
          <tr>
            <td>28 Black Energy Drink</td>
            <td>8.46</td>
            <td align="right">125</td>
            <td align="right">80</td>
            <td align="right">9.5</td>
            <td>ED</td>
          </tr>
          <tr>
            <td>3 Water </td>
            <td>16.9</td>
            <td align="right">0</td>
            <td align="right">50</td>
            <td align="right">3.0</td>
            <td>W</td>
          </tr>
          <tr>
            <td>3D Energy Drink</td>
            <td>16</td>
            <td align="right">15</td>
            <td align="right">200</td>
            <td align="right">12.5</td>
            <td>ED</td>
          </tr>
          <tr>
            <td>4 Purpose Energy Drink</td>
            <td>8.46</td>
            <td align="right">70</td>
            <td align="right">70</td>
            <td align="right">8.3</td>
            <td>ED</td>
          </tr>
          <tr>
            <td>4C Energy Drink Mix</td>
            <td>16.9</td>
            <td align="right">15</td>
            <td align="right">170</td>
            <td align="right">10.1</td>
            <td>ED</td>
          </tr>
          <tr>
            <td>5 Hour Energy</td>
            <td>1.93</td>
            <td align="right">4</td>
            <td align="right">200</td>
            <td align="right">103.6</td>
            <td>ES</td>
          </tr>
          <tr>
            <td>5 Hour Energy Extra Strength</td>
            <td>1.93</td>
            <td align="right">0</td>
            <td align="right">230</td>
            <td align="right">119.2</td>
            <td>ES</td>
          </tr>
        </tbody>
      </table>
    </div>
  </div>
</div>

Comments

0

IMPORTANT!

#IDs ARE UNIQUE!

Do not have more than one of the same #id on a page because it's:

  • invalid HTML
  • semantically gross
  • behavior becomes unpredictable
  • JavaScript if not immediately but eventually break
  • the terrorists win

There's like a ton of these in OP:

<button type="submit" id="myButton">+</button> <!--👎-->

Try to avoid using #id at all -- use .class instead. In the example below the function insertCol() is versatile and reusable. The <table> has a <tfoot> for demonstration purposes. Details are commented in the example.

// This object stores content for insertCol() to fill a table
let content = {
  cap: {
    text: 'TEXT',
    side: '',
    act: 0 // 1='use data' 0='skip data'
  },
  tH: {
    th: 'tH',
    act: 0
  },
  tB: {
    th: '',
    td: `<td><button class="btn btn-sm btn-info add">➕</button></td>`,
    act: 1
  },
  tF: {
    td: 'tF',
    act: 0
  }
};

/**
 * @desc - Inserts a column into a given table
 * @param {number} index - Index to inert new column at
 * @param {object} content - Object that stores content
 * @param {string<selector>} selector - CSS Selector of a 
 *        tag if undefined @default is "table"
 */
function insertCol(index, content, selector = 'table') {
  // Reference <table>
  const table = document.querySelector(selector);
  // Collect all <tr> into an array
  const rowArray = [...table.rows];
  let cols = rowArray[0].cells.length;
  let size = rowArray.length;
  //console.log(size);
  //console.log(cols);

  /*
  If content.tB is active (1)...
  ... .foreach() <tr> add <td> and content at the index
  */
  if (content.tB.act) {
    rowArray.forEach(tr => {
      tr.insertCell(index).innerHTML = content.tB.td;
    });
  }
  /*
  If there's a <thead> AND content.tH.act === 1...
  ... .removeCell() at index...
  ... add <th> with content
  */
  if (table.tHead && content.tH.act) {
    rowArray[0].deleteCell(index);
    rowArray[0].insertCell(index).outerHTML = `<th>${content.tH.th}</th>`;
  }
  // The same as above for <tfoot>
  if (table.tFoot && content.tF.act) {
    rowArray[size - 1].deleteCell(index);
    rowArray[size - 1].insertCell(index).innerHTML = content.tF.td;
  }
  // This block is for <caption>
  if (table.caption && content.cap.act) {
    table.caption.innerHTML = content.cap.text;
    table.caption.style.captionSide = content.cap.side;
  }
}

// -1 is the index after the last index
insertCol(-1, content);
<!DOCTYPE html>
<html lang="en">

<head>
  <title></title>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet">
  <style></style>
</head>

<body>
  <main class="container scrollingTable">
    <section class="row justify-content-center">
      <div class="col-md-8 col-lg-8 mb-8">
        <label class='form-label' for='search'>Search</label>
        <input id="search" class='form-control mb-2' type="text" placeholder="Search for names..">
        <table class='table table-striped table-hover'>
          <caption></caption>
          <thead>
            <tr>
              <th title="Field #1">drinkName</th>
              <th title="Field #2">drinkSizeInFlOz</th>
              <th title="Field #3">calories</th>
              <th title="Field #4">caffeineInMg</th>
              <th title="Field #5">caffeineInMgPerFloz</th>
              <th title="Field #6">type</th>
            </tr>
          </thead>
          <tbody>
            <tr>
              <td>28 Black Energy Drink</td>
              <td>8.46</td>
              <td>125</td>
              <td>80</td>
              <td>9.5</td>
              <td>ED</td>
            </tr>
            <tr>
              <td>3 Water </td>
              <td>16.9</td>
              <td>0</td>
              <td>50</td>
              <td>3.0</td>
              <td>W</td>
            </tr>
            <tr>
              <td>3D Energy Drink</td>
              <td>16</td>
              <td>15</td>
              <td>200</td>
              <td>12.5</td>
              <td>ED</td>
            </tr>
            <tr>
              <td>4 Purpose Energy Drink</td>
              <td>8.46</td>
              <td>70</td>
              <td>70</td>
              <td>8.3</td>
              <td>ED</td>
            </tr>
            <tr>
              <td>4C Energy Drink Mix</td>
              <td>16.9</td>
              <td>15</td>
              <td>170</td>
              <td>10.1</td>
              <td>ED</td>
            </tr>
            <tr>
              <td>5 Hour Energy</td>
              <td>1.93</td>
              <td>4</td>
              <td>200</td>
              <td>103.6</td>
              <td>ES</td>
            </tr>
            <tr>
              <td>5 Hour Energy Extra Strength</td>
              <td>1.93</td>
              <td>0</td>
              <td>230</td>
              <td>119.2</td>
              <td>ES</td>
            </tr>
          </tbody>
          <tfoot>
            <tr>
              <td>FOOT</td>
              <td>FOOT</td>
              <td>FOOT</td>
              <td>FOOT</td>
              <td>FOOT</td>
              <td>FOOT</td>
            </tr>
          </tfoot>
        </table>
      </div>
    </section>
  </main>
  <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script>
  <script></script>
</body>

</html>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.