Nathan Osman
Nathan Osman

Reputation: 73185

How come jQuery can't remove this element?

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.

Upvotes: 0

Views: 3870

Answers (7)

Szurdoki G&#225;bor
Szurdoki G&#225;bor

Reputation: 3

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

Upvotes: 0

George Cummins
George Cummins

Reputation: 28906

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

Upvotes: 0

reinierpost
reinierpost

Reputation: 8591

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.

Upvotes: -2

John K
John K

Reputation: 28869

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.

Upvotes: 0

Marcel Jackwerth
Marcel Jackwerth

Reputation: 54762

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).

Upvotes: 5

Marko Dumic
Marko Dumic

Reputation: 9888

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.

Upvotes: 1

cletus
cletus

Reputation: 625057

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.

Upvotes: 2

Related Questions