2

How do you delete all rows on a table with Javascript except the first one? Here's my code, I want to create a function that removes all rows except the first one and change it to "Your team roster is empty". I need the Javascript code for that.

<script type="text/javascript">
/* <![CDATA[ */
var flag = true;
function addBowler() { 
    if(flag){
        document.getElementById("bowlerList").deleteRow(0);
        flag = false;
    }

    var removeButton = "<input type='button' value='remove' onclick='removePlayer()' /> &nbsp;";
    var newBowler = document.getElementsByName('bowlersName')[0].value;
    var tr = document.createElement('tr');
    var td = tr.appendChild(document.createElement('td'));
    td.innerHTML = newBowler + removeButton;
    document.getElementById("bowlerList").appendChild(tr);
}
function removePlayer() { 
}
/* ]]> */
</script>
</head>
<body>

<!--  HEADER 1 & 2  -->
<h1>Central Valley Lanes</h1>
<h2>2008 Bowling Teams</h2>
<p>Bowler's name:<input type="text" name="bowlersName" size="15" />
<input type="button" value="Add Bowler" onclick="addBowler()" /></p>
<h2>Team Roster</h2>
<form action="FormProcessor.html" method="get" >
<table border="1" id="bowlerList">
<tr><td id="empty">Your team roster is empty</td></tr>
</table>
<p><input type="submit" value="Submit" /></p>
</form>
</body>
2
  • I see jQuery is not an option, can you limit your userbase to CSS3 compliant browsers? if so, you can use almost the same syntax that MJ Hufford suggested document.querySelectorAll("#bowlerList tr:not(:first-child)") will get you an array of elements, then you can iterate through them and document.getElementById("#bowlerList").removeChild(thisElement) them Apr 29, 2013 at 1:58
  • Look at this answer stackoverflow.com/questions/4831334/… Aug 31, 2013 at 21:49

6 Answers 6

9

Can you use jQuery?

$("#bowlerList:not(:first)").remove();

Reference here: jQuery select all except first

5
  • 2
    our professor doesn't want us to use jQuery :S can you translate that to JAvascript? Apr 29, 2013 at 1:47
  • 19
    Your professor? Is this your homework?!? Don't make me give you the lecture I give my kids about doing your own work! :-)
    – MJ Hufford
    Apr 29, 2013 at 1:53
  • 2
    But I really need the code :S I'm tired right now, I just want that removePlayer code Apr 29, 2013 at 1:54
  • 2
    you can achieve something similar with querySelectorAll in Javascript to Jquery in terms of selection. SO members aren't very fond of helping students with their homework (your code right now is visible to the public and if one of your classmates stumbles upon it decides to copy it, well things get messy.) Just a heads up.
    – aug
    Apr 29, 2013 at 2:02
  • 12
    Will I graduate too if I do your assignment?
    – Saturnix
    Apr 29, 2013 at 2:22
7

To delete all of the rows except for the first row (which the first row might be the table's header row) as in your sample code above, the table id is bowlerList

var mytbl = document.getElementById("bowlerList");
mytbl.getElementsByTagName("tbody")[0].innerHTML = mytbl.rows[0].innerHTML;

This is not optimized for speed, but it's easy and fast for deleting many rows at once.

4

There are a number of ways to remove all but the first row. Probably the simplest, and slowest, is to remove the last row until there's only one left:

function clearTable(table) {
  var rows = table.rows;
  var i = rows.length;
  while (--i) {
    rows[i].parentNode.removeChild(rows[i]);
    // or
    // table.deleteRow(i);
  }
}

Or, if there are no listeners on the tBody you can do:

function clearTable(table) {
  var firstRow = table.rows[0];
  var tBody = table.tBodies[0].cloneNode(false);
  tBody.appendChild(firstRow);
  table.replaceChild(tBody, table.tBodies[0]);
}

where table is a reference to a DOM table element. There are many other ways to go about it, the above should work everwhere. To replace the content of the first TD in the first row, you can do:

table.rows[0].cells[0].innerHTML = "whatever";
4
for(var i = 1;i<table.rows.length;){
            table.deleteRow(i);
        }

This simple code will delete all except the first row in any table.

0
1
and change it to "Your team roster is empty". 

If you remove all the rows except the first one, then your "team roster" cannot be empty so I've skipped that part.

I want to create a function that removes all rows except the first one

see code below

<script type="text/javascript">
/* <![CDATA[ */
var flag = true;
var count = 0;
function addBowler() { 
    if(flag){
        document.getElementById("bowlerList").deleteRow(0);
        flag = false;
    }

    var removeButton = "<input type='button' value='remove' onclick='removePlayer()' /> &nbsp;";
    var newBowler = document.getElementsByName('bowlersName')[0].value;
    var tr = document.createElement('tr');
    var td = tr.appendChild(document.createElement('td'));
    td.innerHTML = newBowler + removeButton;
    tr.id = count;
    document.getElementById("bowlerList").appendChild(tr);

    count++;

}


function removeAll(){

    for(var x = 1; x<count; x++)
        removeElement(document.getElementById(x))

    count = 1;

}

function removeElement(el) {
el.parentNode.removeChild(el);
}
/* ]]> */
</script>
</head>
<body>

<!--  HEADER 1 & 2  -->
<h1>Central Valley Lanes</h1>
<h2>2008 Bowling Teams</h2>
<p>Bowler's name:<input type="text" name="bowlersName" size="15" />
<input type="button" value="Add Bowler" onclick="addBowler()" /></p>
<h2>Team Roster</h2>
<form action="FormProcessor.html" method="get" >
<table border="1" id="bowlerList">
<tr><td id="empty">Your team roster is empty</td></tr>
</table>
<p><input type="submit" value="Submit" /></p>
<input type="button" value="removeall" onclick="removeAll()"/>
</form>
</body>
5
  • Why are there three new functions? :O Apr 29, 2013 at 1:58
  • -1 for using jQuery after OP advises he cannot use it, when it is also not tagged Edit: no wait - I see that is in the OP's original code... which is odd. I withdraw my -1 good sir Apr 29, 2013 at 1:59
  • You didn't noticed i didn't used any JQuery? I've just pasted the code from the OP and leaved the function there. It is not even used.
    – Saturnix
    Apr 29, 2013 at 2:00
  • The OP changed the question as I was writing the code - there are NO new functions. Those are just functions that were originally in your code. Next time plan carefully your question before posting, otherwise users willing to help may get downvotes.
    – Saturnix
    Apr 29, 2013 at 2:01
  • 2
    @ambonjingness "Can someone modify this code..." gets dangerously close to "Please do this for me because the internet is a source of free labour" You're likely to get a better response if you have a play with the code that has been given to you generously first and see if you can make it work yourself, then comment with what you have tried and the results if you can't figure it out. As this seems like a College/University/School project you will also get the most value out of your education this way. Apr 29, 2013 at 2:07
0

The first row always has the index of 0. So just loop through using for loop and deleteRow(1). The logic being every row will eventually be row (1) at some point. After the loop you can then check for the table row count. Using table.rows.length. If it is equal to one then print your table is empty.

1
  • 1
    Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.
    – Community Bot
    May 17, 2022 at 21:05

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.