最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How do I remove() an HTML element and then prepend() it? - Stack Overflow

programmeradmin6浏览0评论

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.

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.

Share Improve this question asked Oct 9, 2011 at 11:27 Moe SweetMoe Sweet 3,7212 gold badges36 silver badges46 bronze badges
Add a ment  | 

6 Answers 6

Reset to default 4

The plain js way is:

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

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

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

jQuery prepend

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

is probably the easiest way

Like this ? :

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

Fiddle : http://jsfiddle/Z3VrV/1/

Or this :

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

Fiddle : http://jsfiddle/Z3VrV/2/