1

I am trying to create a new row using a javascript function. I've already reviewed all of the of the previously answered questions but non of them helped. this is my code if this helps out any:

var deleteRow = document.getElementsByClassName('gone');

function removeParent(){
  this.parentNode.parentNode.remove();
}

for(var i = 0; i < deleteRow.length; i++) {
  deleteRow[i].addEventListener("click", removeParent);
}

var addRow = document.getElementsByClassName('add');

function addRow(){
  var deleteRow = table.insertRow(0);
}

for(var i = 0; i < addRow.length; i++) {
  addRow[i].addEventListener("click", addRow);
}
3
  • use jquery, this will make things easy Commented Nov 14, 2015 at 20:22
  • The problem is I haven't used jquery, I have no experience in it yet @mapodev Commented Nov 14, 2015 at 20:23
  • Is there no way to do it with just a basic Javascript code ? Commented Nov 14, 2015 at 20:24

1 Answer 1

2

Try this code

function myCreateFunction() {
    var table = document.getElementById("myTable");
    var row = table.insertRow(0);
    var cell1 = row.insertCell(0);
    var cell2 = row.insertCell(1);
    cell1.innerHTML = "NEW CELL1";
    cell2.innerHTML = "NEW CELL2";
}

function myDeleteFunction() {
    document.getElementById("myTable").deleteRow(0);
}

And use this html

<p>Click the buttons to create and delete row(s) for the table.</p>

<table id="myTable">
   <tr>
      <td>Row1 cell1</td>
      <td>Row1 cell2</td>
   </tr>
   <tr>
      <td>Row2 cell1</td>
      <td>Row2 cell2</td>
   </tr>
   <tr>
      <td>Row3 cell1</td>
      <td>Row3 cell2</td>
   </tr>
</table>

<button onclick="myCreateFunction()">Create row</button>
<button onclick="myDeleteFunction()">Delete row</button>
Sign up to request clarification or add additional context in comments.

4 Comments

Thank you @Endrit Shala but this didn't work this is the same example from w3 school if you take a look at my code you can see the way i did it before, this code didn't work with my code.
First function needs to be named myCreateFunction not myFunction to match onclick attribute.
@DivineComedian Thank you that you told me.
@Villainy Well what you're asking this is what you have to do maybe try to change the question because you want something else.

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.