rwkiii
rwkiii

Reputation: 5846

Replace entire table row (including <tr></tr>) using JQuery

I've looked at other examples here, but they seem to be replacing the contents of a <tr> and not the entire row including the <tr>.

<table>
    <tr style="display:block">
        <td id="someid">Test</td>
        <td>Some text</td>
    </tr>
</table>

The following code seems to only replace the innerHTML of the <tr>. I need to replace everything, including the <tr> so that the row will collapse. Can anyone confirm that this code does or does not completely replace the row:

var newtr = "<tr style='display:none'><td id='someid'></td><td></td></tr>"
$("td#someid").parent().html(newtr);

The reason why I don't think the entire <tr> is being replaced is because the row doesn't collapse - though I have tested the HTML outside of JQuery and it works fine.

Upvotes: 9

Views: 36230

Answers (7)

Umair Noor
Umair Noor

Reputation: 442

you can also check this JsFiddle

var newtr = "<tr style='display:none'><td id='someid'></td><td></td></tr>";

$("td#someid").parent().parent().html(newtr);

Upvotes: 1

Ahsan Rathod
Ahsan Rathod

Reputation: 5505

See this Demo: http://jsfiddle.net/rathoreahsan/QXmTN/

Jquery

$("td#someid").parent().replaceWith(newtr);

Upvotes: 1

jaypeagi
jaypeagi

Reputation: 3141

If you prefer the HTML technique as opposed to switching out elements, try this:

You are correct in saying that this will not replace the tr element. .html("...") replaces the inner HTML of the element (the tr in this case). Use the JavaScript outerHTML to achieve this: $("td#someid").parent().get(0).outerHTML = newtr;

Upvotes: 1

Adil
Adil

Reputation: 148160

Use replaceWith method of jquery to replace the element.

$('#someid').parent().replaceWith(newtr);

Upvotes: 2

John Green
John Green

Reputation: 13435

If you're trying to replace the object, not its contents:

$("td#someid").parent().replaceWith(newtr);

Upvotes: 2

Jon
Jon

Reputation: 437684

The proper function is .replaceWith:

$("td#someid").parent().replaceWith(newtr);

Upvotes: 3

Peter Olson
Peter Olson

Reputation: 142997

You're almost there, just use the jQuery replaceWith[jQuery docs] function:

$("td#someid").parent().replaceWith(newtr);

Upvotes: 27

Related Questions