Css selector syntax to delete <td> element with jQuery

Asked

Viewed 301 times

2

Some way to use jquery and selectors in a way similar to this?

$("#tabela td").empty();

I need to delete only the lines tr containing td of a table like this, but not the rows tr which contain elements th.

The way I’m doing, eliminate the td, but not the tr containing td.

<table id = "tabela">
    <tr>
        <th>title</th>
    </tr>
    <tr>
        <td>teste</td>
    </tr>
</table>

3 answers

3


I suggest you do as you started and add .closest('tr') so he goes up to the element tr and can remove it.

$("#tabela td").closest('tr').empty(); // ou .remove();

example: http://jsfiddle.net/47T9T/

  • It’s all right, just remove the tr's with td's in this way.

0

I had not used it before, but I believe it is okay to continue using it. In my case, I usually use the Closest (http://api.jquery.com/closest/) and remove it (http://api.jquery.com/remove/), passing the element that received the click.

For example:

<!-- tabela --> <table> <tr> <td>Asdf</td> <td><a onclick="excluir(this)">Excluir</a></td> </tr> </table>

<!-- script --> // Irá encontrar a primeira ocorrência TR a partir do elemento (no caso, o link) e fazer a ação que mandarmos (no caso, excluir a tr toda). function excluir(element){ $(element).closest('tr').remove(); }

  • Hi, I updated the question, if you want to update your answer..

  • You can use the same idea, changing only what you want to actually delete. But I think in your case the option of Tiago César Oliveira above is a good.

0

Your dial is almost correct.

For the HTML markup below

<table id="tabela">
    <tr>
        <th>Linha com TH</th>
    </tr>
    <tr>
        <td>Linha com TD</td>
    </tr>
</table>

This JS code solves the problem

$("#tabela td").closest("tr").remove();

Example: http://jsfiddle.net/Npx67/1/

Edit1 to meet the requirement

Browser other questions tagged

You are not signed in. Login or sign up in order to post.