Moving Tags in DOM using jQuery


Introduction


I this quick post you will learn how to move any tag in DOM using jQuery. Firstly, I will show you a problem and then I will talk on its fixes. Here's a problem:

My friend has designed a web page that has following information inside <body> tag. He is actually novice in web.

<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 copyright information at wrong location that is inside <div> having class "mainBodyInfos". Means <div> that has class "CopyrightInfo" should be after <div> that has id "footerInfos". Look at the screen:


Above image shows the actual location of copyright information.
Here, jQuery come for rescue. Let's look at jQuery code:


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

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

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

If you want to dive-in for some more learning on this topic, you can try following alternatives yourself.

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

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

Comments

Popular posts from this blog

Migrating database from ASP.NET Identity to ASP.NET Core Identity

Customize User's Profile in ASP.NET Identity System

Lambda two tables and three tables inner join code samples