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开发者_如何学C jQuery.
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.net/Z3VrV/1/
Or this :
$("#row3").click(function () {
$(this).parent(":first-child").before($(this));
})
Fiddle : http://jsfiddle.net/Z3VrV/2/
精彩评论