Tomkay
Tomkay

Reputation: 5160

Change position of tags in the DOM

<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?

Upvotes: 1

Views: 727

Answers (5)

erimerturk
erimerturk

Reputation: 4288

function doWorks(){

    var h3 = $("h3");

    h3.remove();

    h3.insertBefore("p");


}

Upvotes: 1

GregL
GregL

Reputation: 38113

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

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

jsFiddle proof.

Upvotes: 4

Arif
Arif

Reputation: 196

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

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

Upvotes: 1

scessor
scessor

Reputation: 16115

With jQuery:

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

Also see my jsfiddle.

Upvotes: 2

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324630

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.parentNode.insertBefore(h3elem, pelem);

This moves the h3 to before the p.

Upvotes: 1

Related Questions