Moving Tags in DOM Using jQuery

Introduction

In this quick article you will learn how to move any tag in the DOM using jQuery. I will first show you a problem and then I will explain its fixes. Here's a problem:

One of my close friends has designed a web page that has the following information in the <body> tag. He is actually a novice in webs.

<body>

    <div style="width: 500px; text-align: justify;">

        <h2>History of Visual Studio</h2>

        <div class="mainBodyInfos">
           
<div class="CopyrightInfo">

                Copyright © 2009-2012 ITORIAN. All rights reserved.

            </div>

            Visual Studio's history probably begins in 1975 with Bill and Paul's decision to create Altair BASIC.  Maybe you could start before that but I think that's as far back as you could go and still say it's about Visual Studio at all – it's at that time that Microsoft decided it was going to have software development products and not, say, toaster automation.

            ...

        </div>

        <div id="footerInfos">

            Footer Informations.

        </div>

    </div>

</body>

Can you see any mistake above? If not, let me tell you, by mistake he placed the copyright information at the wrong location; that is, inside the <div> having the class "mainBodyInfos". Which means that the <div> that has the class "CopyrightInfo" should be after the <div> that has the id "footerInfos". Look at the screen:

image001.png

The above image shows the actual location of the copyright information.

Here, jQuery comes to the rescue. Let's look at the jQuery code:

image002.png

Just a single line of jQuery code (given below) can rescue this.

$('div.CopyrightInfo').insertAfter('#footerInfos');

Using the above, I am searching for the "CopyrightInfo" <div> class and inserting it after a <div> that has the id "footerInfos".

If you want to dive in to learn more on this topic, you can try the following alternatives yourself.

.insertBefore() or .prependTo() and .appendTo()

I have also attached my sample project above, download and test it.