改变DOM中标签的位置

Change position of tags in the DOM

本文关键字:位置 标签 DOM 改变      更新时间:2023-09-26
<p>I like turtles</p>
<h3>Child brags about stuff</h3>
<h4>The Herd</h4>

如何更改标签的位置(顺序)?

:

<h3>Child brags about stuff</h3>
<p>I like turtles</p>
<h4>The Herd</h4>

是否有JQuery的可能性?

使用.detach().insertAfter()的jQuery方法,如下:

$(function() {
   $('p').detach().insertAfter('h3'); 
});

jsFiddle证据。

使用jQuery:

$('h3').after($('p'));

如果你在变量h3elem中有h3,在pelem中有p(无论你想在那里获得它们- jQuery, getElementByIdgetElementsByTagName,或任何东西),使用:

h3elem.parentNode.insertBefore(h3elem, pelem);

h3移动到p之前。

下面的代码将在<p>标签之前插入<h3>标签,您可以为它们分配一个id来唯一标识它们。

$('h3').insertBefore($('p'));

function doWorks(){
    var h3 = $("h3");
    h3.remove();
    h3.insertBefore("p");

}