更改DOM中标记的位置

时间:2021-06-20 20:15:38
<p>I like turtles</p>
<h3>Child brags about stuff</h3>
<h4>The Herd</h4>

How do I change the positions (order) of a tag?

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

To this:

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

Is there a JQuery possibility?

有JQuery的可能性吗?

5 个解决方案

#1


4  

Use .detach() and .insertAfter() jQuery methods, like so:

使用.detach()和.insertAfter()jQuery方法,如下所示:

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

jsFiddle proof.

#2


2  

With jQuery:

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

Also see my jsfiddle.

另见我的jsfiddle。

#3


1  

If you have the h3 in the variable h3elem and the p in pelem (get them there however you want - jQuery, getElementById or getElementsByTagName, or anything really), use:

如果你有变量h3elem中的h3和pelem中的p(无论你想要它们 - jQuery,getElementById或getElementsByTagName,还是其他任何东西),请使用:

h3elem.parentNode.insertBefore(h3elem, pelem);

This moves the h3 to before the p.

这将h3移动到p之前。

#4


1  

The below code will insert <h3> tag before <p> tag, you can assign them an id to identify them uniquely.

下面的代码将在

标记之前插入

标记,您可以为它们分配一个ID来唯一地标识它们。

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

#5


1  

function doWorks(){

    var h3 = $("h3");

    h3.remove();

    h3.insertBefore("p");


}

#1


4  

Use .detach() and .insertAfter() jQuery methods, like so:

使用.detach()和.insertAfter()jQuery方法,如下所示:

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

jsFiddle proof.

#2


2  

With jQuery:

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

Also see my jsfiddle.

另见我的jsfiddle。

#3


1  

If you have the h3 in the variable h3elem and the p in pelem (get them there however you want - jQuery, getElementById or getElementsByTagName, or anything really), use:

如果你有变量h3elem中的h3和pelem中的p(无论你想要它们 - jQuery,getElementById或getElementsByTagName,还是其他任何东西),请使用:

h3elem.parentNode.insertBefore(h3elem, pelem);

This moves the h3 to before the p.

这将h3移动到p之前。

#4


1  

The below code will insert <h3> tag before <p> tag, you can assign them an id to identify them uniquely.

下面的代码将在

标记之前插入

标记,您可以为它们分配一个ID来唯一地标识它们。

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

#5


1  

function doWorks(){

    var h3 = $("h3");

    h3.remove();

    h3.insertBefore("p");


}