Arun Kumar
Arun Kumar

Reputation: 75

Removing <tr> using javascript

How can i remove entire <tr> from a table using javascript without using getElementByID because i do not have any IDs of table tr or tds

Upvotes: 1

Views: 5366

Answers (4)

srini
srini

Reputation: 884

try something like this

        <html>
        <head>
          <style>
        </style>
          <script src="http://code.jquery.com/jquery-latest.js"></script>
        </head>
        <body>
         <table>
         <tr>
          <td>test</td><td>test</td><td>test</td>
         </tr>
         <tr>
          <td>test</td><td>test</td><td>test</td>
         </tr>
         </table>

        <button>Empty</button>
        <script>
          $("button").click(function () {
            $("table").empty();
          });
        </script>

        </body>
        </html>

Upvotes: 0

dragon66
dragon66

Reputation: 2715

Assume your table has id="mytable":

This is how you get all the trs:

1. var trs = document.getElementById("mytable").rows; or
2. var trs = document.getElementById("mytable").getElementsByTagName("tr");

Now do this:

while(trs.length>0) trs[0].parentNode.removeChild(trs[0]);

If you don't have id for your table and you have only one table on the page, do this:

var trs = document.getElementsByTagName("table")[0].rows;

It would be hard to remove a specific tr if you don't give it an id. If you want to remove certain kind of trs, give them a class attribute and remove only those trs with this class attribute.

Upvotes: 5

Jezen Thomas
Jezen Thomas

Reputation: 13800

You could try something like this with jQuery:

$(function(){
    $('tr, td').remove();
});

Or if — for whatever reason — you'd like to remove all contents of a table:

$('table').empty();

Upvotes: 2

Quentin
Quentin

Reputation: 943537

Once you have identified the <tr> you wish to remove (you haven't provided enough context to your question to suggest (without making lots of assumptions) how you might do that):

tr_element.parentNode.removeChild(tr_element)

Upvotes: 1

Related Questions