Question

I have a table like this:

<table id='inventory_table'>
  <tr id='no_items_avail'>
    <td>
      There are no items in the database.
    </td>
   </tr>
</table>

And I want to get rid of it with jQuery like this:

$('#inventory_table tbody tr#no_items_avail').remove();

However it doesn't seem to be working at all. What am I doing wrong?

Edit: Also, the row above was originally inserted into the DOM with another jQuery call:

$('#inventory_table tbody').append("<tr id='no_items_avail'.......

If that helps. And, running:

alert($('#no_items_avail').text());

yields "There are no items in the database." as expected.

Was it helpful?

Solution

My guess is that you are using the same ID more than once in the same document? Because this works perfectly for me on IE8 (compatibility mode), FF and Chrome.

Of course it doesn't need to be that complex as this works perfectly:

$("#no_items_avail").remove();

Just remember that IDs have to be unique and duplicating them is a common reason why this kind of thing fails.

OTHER TIPS

You assume tbody to be available in your DOM. Only a few browsers add tbody to a table if it does not exist. Try

$('#inventory_table tr#no_items_avail').remove();

or even better

$('#no_items_avail').remove();

(since IDs must be unique anyway).

Your selector is unnecessary large. This is shorter and it works: $('#no_items_avail').remove();​​​​​

Also, make sure you have no other elements with same id.

Try using dash '-' in your ids instead of underscore. I believe some browsers don't react well to underscores. Maybe I'm thinking about CSS instead of JS but give it a try for what it's worth.

Your selector references a non-existant tbody:

$('#inventory_table tbody tr#no_items_avail').remove();

Remove 'tbody' and it should work:

$('#inventory_table tr#no_items_avail').remove();

Alternately, just reference the tr ID itself:

$('#no_items_avail').remove();

You have no <tbody> tag in the table. The jQuery selection "stops" after not finding it.

1) Don't use IDs to identify stuff with jQuery, use classes or possibly path-based selection. 2) Don't add and remove content, show and hide it instead.

Dynamically changing your page content in arbitrary ways is not going to help maintainability, so I hope what you're doing well disciplined, in some way, and well documented. Think of the poor sod who will have to take over when you get hit by a bus or win the lottery.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top