Revamp the sequence of divs using jQuery

<div class="example first">111</div>
<div class="example second">222</div>
<div class="example third">333</div>

Can the order of these divs be changed using jQuery? I am looking to get:

<div class="example second">222</div>
<div class="example third">333</div>
<div class="example first">111</div>

I only have access to jQuery for this task.

LIVE: http://jsfiddle.net/cmVyM/

This change will only occur once the document has fully loaded.

Answer №1

It seems like you're interested in moving the first div after the last one.

$.fn.insertAfter places the selected elements after a specified parameter:

$(".test.one").insertAfter(".test.three");

http://jsfiddle.net/rP8EQ/

Edit: For a more universal approach of moving the first element after the last one, without relying on specific classes:

var tests = $('.test');
tests.first().insertAfter(tests.last());

Answer №2

Check out this straightforward example featuring navigation buttons.

HTML Content

<ul>
  <li>1 <a class='up' href='#'>move up</a> <a class='down' href='#'>move down</a></li>
  <li>2 <a class='up' href='#'>move up</a> <a class='down' href='#'>move down</a></li>
  <li>3 <a class='up' href='#'>move up</a> <a class='down' href='#'>move down</a></li>
  <li>4 <a class='up' href='#'>move up</a> <a class='down' href='#'>move down</a></li>
  <li>5 <a class='up' href='#'>move up</a> <a class='down' href='#'>move down</a></li>
  <li>6 <a class='up' href='#'>move up</a> <a class='down' href='#'>move down</a></li>
</ul>

Interactive JavaScript using JQuery

$('.up').on('click', function(e) {
    var container = $(this).closest('li')
    container.insertBefore(container.prev())
})
$('.down').on('click', function(e) {
    var container = $(this).closest('li')
    container.insertAfter(container.next())
})

Experiment with it here on JSFiddle

Answer №3

To move element with class "one" after element with class "three", you can simply use the jQuery function: $('.one').insertAfter('.three');

Answer №4

$("#button").click(function(){       

$("#third").insertBefore("#first");   

}); 

<div id="first">a1</div>
<div id="second">a2</div>
<div id="third">a3</div>

<div>
<a id="button">change</a>
</div>

Reference: http://jsfiddle.net/GeraldoVilger/2B6FV/

Answer №5

To achieve this, simply use the insertAfter function as suggested in the previous response

http://jsfiddle.net/cmVyM/68/

var first = $('.one');
var second = $('.two');
var third = $('.three');

second.insertAfter(third);
first.insertAfter(second);

Answer №6

To rearrange a series of divs with the same class name (example provided below):

<div class="wrapper">
  <span class="text">First Heading</span>
  <span class="number">1</span>
</div>
<div class="wrapper">
  <span class="text">Second Heading</span>
  <span class="number">2</span>
</div>
<div class="wrapper">
  <span class="text">Third Heading</span>
  <span class="number">3</span>
</div>

You can use the jQuery code below to reorder them:

$('.wrapper .number').each(function () {
  $(this).insertBefore($(this).prev('.text'));
});

https://jsfiddle.net/farhanmae/9th3drvd/

Answer №7

Another option to achieve the same result is by using JQuery's appendTo method.

You can create a copy of $('.one') element and store it in a variable called nav.
Then you can remove the original $('.one') element from the DOM.
Finally, you can append the copied element stored in 'nav' to '.three'.

var nav = $('.one').clone(true);
$('.one').remove();
nav.appendTo('.three');
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<div class="test one">aaa</div>
<div class="test two">bbb</div>
<div class="test three">ccc</div>

Answer №8

Here is a simple way to achieve this:

var element = $('.element.target');

element.after(element.prev());

By implementing the above code, you can change the positions of two specific div elements.

I trust this solution will work for you.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Having trouble accessing the menu in the dropdown div when clicking back?

I am working on creating a menu that drops down from the top of the page using JQuery. I have everything set up with the code below: <div id="menu"> <div id="menucontentwrapper"> <div id="menucontent"></div> </di ...

Struggling to get the hang of CSS animation?

Here is a code snippet that I am using: //Code for animating skills on view document.addEventListener("DOMContentLoaded", function(event) { function callback(observations, observer) { observations.forEach(observation => { if (observati ...

What is the best way to assess each item in an array and apply the useState() hook based on a specific condition

I am currently working on a simulation for a blackjack hand and have run into an issue with my code. The game follows these steps: users receive two random cards and a total point value, then click 'hit' to draw another random card from the deck. ...

I am unable to locate the type definition file for 'core-js' at the moment

Currently, I am in the process of developing an application using angular2 along with angular-cli. Surprisingly, angular-in-memory-web-api was not included by default. In order to rectify this, I took the initiative to search for it and manually added the ...

Assign a value to an element based on a specific attribute value

I'm working with the following element <input type="text" size="4" name="nightly" value="-1"> My goal is to update the value to 15.9 specifically when name="nightly" Here's what I've attempted so far: document.getElementsByName(&ap ...

Unable to call component method after exporting with connect in React Redux

My React class component features a method that I would like to access later through the provider. Take a look at the class below: class ContactList extends Component { // props for contact renderContacts = () => { return // something }; ...

Transitioning from clip to clip-path in order to utilize percentage values

My current approach involves using a scss-based animation to create border animations with movement. The animation's core functionality relies on the use of clip. $box-width: 80px; $box-height: 50px; @keyframes clipMe { 0%, 100% { ...

Display 1 row of content on larger LG screens and 2 rows on medium-sized MD screens using Bootstrap

How can I achieve 1 row with 12 cells on a large screen in Bootstrap, and for a smaller screen have 2 rows with 6 cells? Here is a visual representation of what I am trying to accomplish: https://i.stack.imgur.com/NgfaP.png This is the code I attempted: ...

Currently in the process of developing an electron application, I encountered an Uncaught Exception error stating: "TypeError: $.ajax is not

I'm currently working on an electron app that interacts with an API endpoint and displays the response on the page. Due to electron's separation of main process and renderer process, I'm using a preload script to facilitate communication bet ...

Scalable Vector Graphics Form Field

I'm looking to enable user input in one of my SVG text fields when they click on it. Any ideas on how to achieve this? const wrapper = document.getElementById('wrapper'); const text = document.getEl ...

Retrieve the added attribute value of a RadioButton using JQuery

Currently, I am faced with a frustrating issue. On my website, I have a RadioButton to which I added an attribute as shown below: in ...asp <div id="radio" class="C_Radio"> <asp:RadioButton id="rad1" GroupName="typeSelect" runat="server" ...

There seems to be a request for an unknown parameter '1' in the data table row

My Datatable is structured as follows: <br><button id="addRow">Add New Row</button><br> <table class="table table-striped table-bordered table-hover " id="example" cellSpacing=0 width="100%"> <the ...

Click on the next tab within the ExtJS tab menu

I am looking to deactivate a tab and if it happens to be active, I want the system to automatically switch to the next tab. I attempted myPanel.tab.disable(); if(myPanel.tab.active) myPanel.NextSibling().tab.setActive(); and myPanel.tab.disable(); ...

Tips for incorporating a Survey Monkey website embed into an Angular application

I have a Survey Monkey account with multiple surveys. I am trying to embed a survey from this website into my Angular website, which already has Bootstrap and jQuery added. I attempted to directly add the script in an HTML component, but it did not work. ...

Accessing Ionic rootScope within the config stateprovider - A step-by-step guide

Is it possible to access the value of $rootScope in the following line? .config(function($stateProvider, $urlRouterProvider) { $stateProvider // I am trying to retrieve the value of $rootScope here. } ...

Ways to monitor the status of a server request using jQuery (ajax)?

I am currently working on a PHP application that involves users submitting forms to the server via ajax (jQuery). The server needs to insert a large number of records into a MySQL database, which may take some time due to various calculations. My question ...

Solving the Cross-Origin Resource Sharing problem in AngularJS

While using the http dependency in AngularJS and setting headers for CORS, I am encountering an error. Please check the console.log for more information on the error. The error message reads: "XMLHttpRequest cannot load . Response to preflight request doe ...

Another option instead of using the .siblings() method would be

Is there an alternative to using the .siblings() method in jQuery for traversing through divs of a specific class in separate container divs? How can this be achieved with the following code: HTML: <div id="container1"> <div id="1"></di ...

The Angular Material date picker unpredictably updates when a date is manually changed and the tab key is pressed

My component involves the use of the Angular material date picker. However, I have encountered a strange issue with it. When I select a date using the calendar control, everything works fine. But if I manually change the date and then press the tab button, ...

Understanding Vue.js - encountering the error message "property or method is not defined"

Recently, I've come across an issue that seems to be common among many people, but for some reason, I am unable to find a solution despite looking at similar questions. The problem arises when I use a v-for in a Vue Component and the array value cons ...