Moe Sweet
Moe Sweet

Reputation: 3721

How do I remove() an HTML element and then prepend() it?

Basically what I need to do is to "move" an HTML element, not position-wise but location of it's DOM structure.

Eg

<table id="main">
<tr id="row1"><td></td></tr>
<tr id="row2"><td></td></tr>
<tr id="row3"><td></td></tr>
</table>

How do I move "tr#row3" to the top of "table#main"? Can use jQuery.

Upvotes: 0

Views: 1902

Answers (6)

Felix Kling
Felix Kling

Reputation: 816334

Another way:

$('#main tbody').prepend(function() {
    return $(this).find('#row3');
});

or you could also do:

$('#main tbody').prepend($('#row3'));

as IDs are supposed to be unique.

Note that although you don't specify a tbody element, the browser will always insert one. That's why you cannot just prepend the row to the table element.

Update: To be correct, in fact you can, as @Šime Vidas pointed out.

Reference: prepend

Upvotes: 3

adeneo
adeneo

Reputation: 318182

Like this ? :

$("#row3").mouseenter(function () {
    $("#row1").before($(this)); 
})

Fiddle : http://jsfiddle.net/Z3VrV/1/

Or this :

$("#row3").click(function () {
    $(this).parent(":first-child").before($(this)); 
})

Fiddle : http://jsfiddle.net/Z3VrV/2/

Upvotes: 0

RobG
RobG

Reputation: 147363

The plain js way is:

var row = document.getElementById('row3');
var parent = row.parentNode;
parent.insertBefore(row, parent.firstChild);

Upvotes: 4

genesis
genesis

Reputation: 50966

var row3 = $("tr#row3")
$("#main").prepend(row3);
row3.remove();

is probably the easiest way

Upvotes: 0

var row = table.find("#row3");
var parent = row.parent(); // because parent may not be #main
parent.prepend(row.detach());

In general if you want to more an element, while preserving all of its data, you should use the jQuery .detach() method [docs]. Once you detach the element from its current location it can be inserted into the new one.

However in this case .prepend() and .append() will actually do what you want by default, so .detach() isn't necessary. From the docs:

If a single element selected this way is inserted elsewhere, it will be moved into the target (not cloned):

Upvotes: 3

neworld
neworld

Reputation: 7793

jQuery prepend

var el = $('#row3');
$('#main').prepend(el);

Upvotes: 2

Related Questions