1

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

  • after the last row in the table?
1

2 Answers 2

2

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)
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, It Solves it! :)
1

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>

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.