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

When attempting to convert large objects into JSON using JSON.stringify, a RangeError is thrown due to

Trying to convert a massive JavaScript Object into a string using JSON.stringify in my Node.js application. The objects are extremely large (tens of mega bytes) and do not contain any functions. I need to save the serialized objects to a file. However, I a ...

Steps for creating a resizable and automatically hiding side menu

I am working on a side menu that can be resized, and I want it to collapse (set to zero width) when it is empty. I have considered implementing one of these features individually, but I'm not sure how to make both work together. Is there a way to ad ...

In TypeScript, an interface property necessitates another property to be valid

In the scenario where foo is false, how can I designate keys: a, b, c, bar as having an undefined/null/optional type? Put simply, I require these properties to be classified as mandatory only when foo is true. interface ObjectType { foo: boolean; a: nu ...

Removing characters from a string with regular expressions

I need to eliminate instances of << any words #_ from the given text. stringVal = "<<Start words#_ I <<love#_ kind <<man>>, <<john#_ <<kind man>> is really <<great>> <<end words#_ "; The d ...

Javascript code experiences a shift in two different styles within a single conditional statement

I'm new to web design and I'm having trouble getting this code to work properly. Can anyone help me fix it so that both styles are applied correctly? // Access the sign_up modal window var modal = document.getElementById('id01'); // A ...

Issue encountered when trying to remove an event while a dialog is closed in a React useEffect

While working with my open dialog, I attempted to include a 'key-down' event. Unfortunately, the event continues to trigger even after the dialog is closed. To address this issue, I encapsulated the event handling function within the useEffect h ...

Understanding the Document.ready function?

Recently, I came across some websites that follow this specific pattern: <html> <head> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script> <script> $(function (){...do some stuff with p ...

What is the procedure for eliminating the underline located at the bottom of the table?

Can anyone please assist me with removing the underlines at the end of the table? I find it quite unattractive and can't seem to figure out how to remove it. https://i.sstatic.net/stvHt.png https://i.sstatic.net/YYbrX.png Below is the code snippet ...

What is preventing the element from being positioned at the bottom of the container?

I have a vertical bar chart with 5 different colored sub-containers. I'm trying to position the 'chicken' sub-container at the bottom of the bar without any bottom-margin, but so far my attempts have been unsuccessful. When I try using absol ...

Maintaining photo proportions in HTML when using width and height as percentages

Is it possible to specify width and height as percentages in the <img> attributes? It seems that when I attempt to do so, the image resizes but the quality appears skewed. Here is an example of my markup with fixed attributes: <img src="#" widt ...

Mastering the CSS Art of Working with Sprite Images and Their Positioning

I am currently working on an educational project as a front-end developer, where I aim to clone the Google homepage. To achieve this, I am utilizing Google's own sprite and here is the image of the sprite that I am using. https://i.stack.imgur.com/YT ...

What is the process of converting the timing from my stopwatch to a standard time format?

I am currently working on a stopwatch project where I log the time into an array. However, when I try to use Math.min(array) or Math.max(array), it returns NaN (not a number). The time format for the stopwatch is like 00:00:15.91 which is not recognized as ...

How to effectively handle asynchronous calls in Node.js using readdir and stat functions

My current project involves implementing a post method on the server side to fetch all files within a specified directory (non-recursively). Below is my code snippet. I am encountering challenges in sending back the response (res.json(pathContent);) with ...

If IE's conditional comments are dysfunctional

Could this be a silly question? I feel puzzled by it. I've been using an if IE conditional statement to address some issues in IE6. In the head section, this is what I have: <!--[if lt IE 7] > <script type="text/javascript" src="js/ie6.js" ...

At times, the AngularJS directive may not be invoked

Here is my custom directive: ppm.directive('focusMe', function($timeout) { return { link: function(scope, element, attrs) { scope.$watch(attrs.focusMe, function(value) { if(value === true) { console.log(& ...

Tips for saving data to a file using the frontend

Is it possible for draw.io to write directly to a local file from my browser without the need for any server app or browser extension? I'm not referring to simply downloading a file, but actually writing to a file. For example, when creating a new dia ...

Implementing coordinate formatting in JavaScript [Node.js]

I'm looking to tweak the JSON output into this specific format: [ 50.87758, 5.78092 ], [ 52.87758, 5.48091 ] and so on. Currently, the output looks like this: [ { lat: 53.1799, lon: 6.98565 }, { lat: 52.02554, lon: 5.82181 }, { lat: 51.87335, l ...

Custom CSS styles for purchasing stocks using percentages

Can someone assist me in fixing the CSS for this custom card within a modal box? <!--Card--> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <input type="text" id="market-searc ...

The search functionality on my website, powered by webapp2 and HTML, is not functioning properly

Upon examination, I noticed that my search term is being transmitted to my handler as an empty string. Here are the key components: This is my HTML form: <form class="navbar-search" action="/search"> <input type="text" class="se ...

AntD Functional Component with Row Selection Feature

Is there a way to retrieve the key of a single element in the table instead of getting undefined? How can I extract the id? Check out this link for more information. const [select, setSelect] = useState({ selectedRowKeys: [], loading: false, }); ...