admin管理员组文章数量:1327661
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 badges6 Answers
Reset to default 4The 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/
本文标签: javascriptHow do I remove() an HTML element and then prepend() itStack Overflow
版权声明:本文标题:javascript - How do I remove() an HTML element and then prepend() it? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742231281a2437259.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论