admin管理员组

文章数量:1326118

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

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

Share Improve this question edited May 3, 2012 at 10:53 Zaheer Ahmed 28.6k12 gold badges76 silver badges112 bronze badges asked May 3, 2012 at 10:49 Arun KumarArun Kumar 751 gold badge2 silver badges8 bronze badges 3
  • 4 Could you read that sentence back and reword it so it makes sense? Also, it'd be handy if you could post the code you have tried. We're not here to do your work for you! – Alex Commented May 3, 2012 at 10:50
  • yes Alex im also not even hiring you for my work, i have done my part and requested people, if u know about this your suggestion are highly appreciable otherwise i have not called you here – Arun Kumar Commented May 3, 2012 at 11:24
  • You've given us no context to work with! I had to read through to the bottom to realise that some click event was what's triggering this. Please try to give AS MUCH detail as possible in your question. We're not mind readers – Alex Commented May 3, 2012 at 11:28
Add a ment  | 

4 Answers 4

Reset to default 5

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.

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();

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)

try something like this

        <html>
        <head>
          <style>
        </style>
          <script src="http://code.jquery./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>

本文标签: htmlRemoving lttrgt using javascriptStack Overflow