abhimanyu
abhimanyu

Reputation: 197

How to insert row in table through Javascript function

I am trying to insert another row into a table with footer.

Here is my code:

function submit(){
        /* Some code here with declarations & value assignings*/

        let tble = document.getElementById("tabl");
        
        let newEl = document.createElement("tr");
        newEl.innerHTML="<td>"+nowSr+"</td> <td>"+taskForm+"</td> <td>"+tagForm+"</td> <td>Rs. "+amountForm+"</td>";

        tble.appendChild(newEl, tble.lastElementChild.previousSibling.lastElementChild);
       }

My function gives me below result: enter image description here enter image description here

As you can see (IN INSPECT ELEMENTS WINDOW) the new row is inserted after the footer. How to add it properly

Upvotes: 1

Views: 146

Answers (2)

FZs
FZs

Reputation: 18619

Don't insert the element directly to the <table> element, but select the <tbody> instead.

You can do that like that:

function submit(){
  let tble = document.getElementById("tabl");
        
  let newEl = document.createElement("tr");
  newEl.innerHTML="<td>"+nowSr+"</td> <td>"+taskForm+"</td> <td>"+tagForm+"</td> <td>Rs. "+amountForm+"</td>";

  tble.querySelector('tbody').appendChild(newEl, tble.lastElementChild.previousSibling.lastElementChild);
}

But you shouldn't use innerHTML to create the row (it could create an XSS vulnerability), use innerText or textContent instead. But that means that you have to create the <td>s differently:

function submit(){
  let tble = document.getElementById("tabl");
        
  let newEl = document.createElement("tr");
  appendTD(newEl, nowSr);
  appendTD(newEl, taskForm);
  appendTD(newEl, tagForm);
  appendTD(newEl, "Rs. "+amountForm);

  tble.querySelector('tbody').appendChild(newEl, tble.lastElementChild.previousSibling.lastElementChild);
}

function appendTD(tr, text){
  const td = document.createElement('td')
  td.innerText = text
  tr.appendChild(td)
}

Upvotes: 2

RenaudC5
RenaudC5

Reputation: 3829

Try puhsing to the tbody intead of the table directly

function addTableRow(){
  const tbody = document.querySelector('#myTable tbody')
  
  const newRow = document.createElement('tr')
  newRow.innerHTML = `<td>Foo</td><td>Bar</td>`
  tbody.appendChild(newRow)
}
<table id="myTable">
  <thead>
    <tr>
      <th>Helo</th>
      <th>World</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Foo</td>
      <td>bar</td>
    </tr>
  </tbody>
</table>

<button onclick="addTableRow()">Add row</button>

Upvotes: 1

Related Questions