Change the order in which two divs (or any other object) are stacked

Is there a simple method using only javascript to change the stacking order of two divs?

Assume I have the following four div elements:

<div id="div1">Div number 1</div>
<div id="div2">Div number 2</div>
<div id="div3">Div number 3</div>
<div id="div4">Div number 4</div>

With (pure) javascript, my goal is to swap the positions of div2 and div3 like this:

<div id="div1">Div number 1</div>
<div id="div3">Div number 3</div>
<div id="div2">Div number 2</div>
<div id="div4">Div number 4</div>

I've been struggling to find a solution for this...

Answer №1

Here is a useful function that allows you to interchange the positions of two elements:

function switchElements(item1, item2) {
    var temp = item2.cloneNode(true);
    item1.parentNode.insertBefore(temp, item1);
    item2.parentNode.insertBefore(item1, item2);
    item2.parentNode.replaceChild(item2, temp);
}

Give it a try here.

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

Unable to display any posts in my React application, no content is being produced

I am currently in the process of developing a blogging site using React by following a tutorial. However, I have encountered an issue where the posts are not appearing on the screen. Here is the link to my GitHub repository: https://github.com/AkshatGarg2 ...

Trouble with CSS Class Showing Up Only When Hovered

My goal is to make the .panel-text element visible only when a user hovers over the panel. I attempted to use the overlay CSS class, but I encountered issues where the text either wouldn't show at all or would always be displayed. Here is what I have ...

The pre tag does not have any effect when added after the onload event

I have been experimenting with a jQuery plugin for drawing arrows, detailed in this article. When using the plugin, this code is transformed: <pre class="arrows-and-boxes"> (Src) > (Target) </pre> into this format: Src --> Target The ...

Learning how to update a database using AJAX, jQuery, PHP, and MySQL can greatly enhance your web development

I am facing an issue with updating a database using AJAX without reloading the page. Even though I receive a success message after making the AJAX call, the database is not getting updated as expected. Here is my code: JS: $('.start-time-class' ...

Bootstrap 4 modal with scrollspy feature for a seamless full-screen experience

I am trying to implement a full-screen modal using Bootstrap 4 that incorporates a scrollspy feature for scrolling the content within the modal body. I have successfully achieved the full-screen aspect, but I am facing issues with making the content scroll ...

Submitting a single form through AJAX can be tricky when dealing with multiple forms generated through a PHP loop. Here's

I want to create a keylogger effect where a form is submitted on keyup. Here's what I have so far: PHP loop form - <form method="post" id="'.$vid.'" class="note-form"> <textarea id="'.$vi ...

Error in fullCalendar where events are appearing on incorrect days in the month view of the current month

https://i.sstatic.net/v8Faj.png My fullcalendar plug-in is causing some trouble. I'm trying to show events in the monthview of the calendar, but when I'm in the current month, events on the same day of the week are not displaying correctly. They ...

What is the best way to handle the resolution of multiple promises as they complete?

Suppose I have three different promises each taking a varying amount of time to resolve - 1000ms, 2000ms, and 3000ms respectively. How can I simultaneously start all the promises and handle them as they get resolved? For instance: let quickPromise = new ...

JavaScript's POST method is failing to fetch data from the API, yet it is able to retrieve data successfully in

I am experiencing issues when trying to retrieve data from an API using JavaScript. The API works fine in Postman, but it is not functioning properly in JavaScript. When I run the code, the console displays an error message stating "Failed to fetch respon ...

Mysterious HTML/CSS element causing page to stretch beyond limits

I am currently updating a website to make it responsive. Check it out here: When the viewport is below 980px in width, a horizontal scroll bar appears and the html/body/container remains at 980px. I've attempted to apply an inline width of 200px to ...

Generating Angular select options dynamically using ng-repeat

I've been struggling for several days now with ngOptions and ngRepeat. I am trying to create a select option for a people control. The REST service is returning an array as shown below. Despite trying various solutions from Stack Overflow and the Angu ...

Using the spread operator in Typescript/Javascript to dynamically add members to an object based on certain conditions

I was exploring a method for conditionally adding members to an object, which I found here Below is the code I came up with: const theobj = { field1: "hello", field2: 1, data: { datafield1: "world", datafield2: 2 }, ...

How can Vue add a class to an element without using v-model:class?

I am faced with the challenge of connecting two elements that are located in different areas of the DOM. The goal is to create a hover effect on one element when the other is interacted with. The first element is within a component and is rendered using t ...

Error Handling with Node.js Sequelize RangeError

Currently, I am in the process of setting up a table to store user sessions. Specifically, I plan to save the IP address as an integer and have been exploring various methods for achieving this. You can find more information on this topic here: IP-addresse ...

Extracting information from secured HTML

I am trying to extract data using a vb.net form from but the retrieved code contains some unnecessary white space, hiding the table I'm interested in. <th width="93">Факт. время прибытия</th> ...

The usage of 'import.meta' is restricted to within modules and cannot be utilized outside of them

I am working on a project that involves Node + Express + Babel + ES6. Within this project, I have the following files: /package.json { "name": "test-backend", "version": "1.0.0", "description": " ...

Unveiling the Mystery: Extracting the URL Parameter in AngularJS

Here is a link localhost/project/#/showprofile/18 I need to retrieve the parameter 18 in my view In the application file named app.js, I have the following configuration: .when('/showprofile/:UserID', { title: 'Show User Profile&apo ...

Changing the size of a div using jQuery

I'm attempting to adjust the size of a div element. You can view my progress in this code fiddle: https://jsfiddle.net/bj3m24ks/31/ Kindly refrain from sharing links to other tutorials as I have already explored them all. I attempted to utilize the $ ...

Update my redirect functions in React Js

I've come across a situation where I have multiple components checking if the user is authenticated to redirect to the login page. componentWillReceiveProps({auth}) { if (auth) { this.props.history.push('/login') } } I fin ...

Can you please verify my account by sending a confirmation email and entering my password?

I've been struggling to check in my category controller if a user is logged in, allow them to post a category. Otherwise, show them "You must be logged in to create a category." The problem I'm facing is that the category gets posted whether the ...