How can I rearrange divs using CSS? Can I add parent 1 in between the children of parent 2

Check out my current HTML code structure:

<div class="container>
    <div class="parent1"></div>
    <div class="parent2">
         <div class="child1"></div>
         <div class="child2"></div>
    </div>
</div>

I'm aiming for the following HTML structure:

<div class="container>
    <div class="parent2">
         <div class="child1"></div>
              <div class="parent1"></div>
         <div class="child2"></div>
    </div>
</div>

Do you know if it's achievable using solely CSS or JavaScript (without jQuery)? Even if the HTML elements don't physically move, as long as they are displayed in that specific order on the webpage, I would be satisfied.

Answer №1

You have the ability to achieve this using Javascript:

document.querySelector('.child1').appendChild(document.querySelector('.parent1'));

Presentation:

function rearrange() {
  document.querySelector('.child1').appendChild(document.querySelector('.parent1'));
}
.container * {
  display: block;
  border: 2px solid lightgrey;
  color: lightgrey;
  padding: 5px;
  margin: 15px;
}
.parent1 {
  color: red;
  border-color: red;
}
.child1 {
  color: blue;
  border-color: blue;
}
<div class="container">
<div class="parent1">I'm parent 1!</div>
<div class="parent2">
    I'm parent 2!
         <div class="child1 ">I'm child 1!</div>
         <div class="child2 ">I'm child 2!</div>
    </div>
</div>
<button onclick='rearrange();'>Rearrange!</button>
Note: Css is purely for aesthetic purposes

Answer №2

Utilizing Javascript:

//Eliminate the first parent div from the container
 document.getElementsByClassName('container')[0].removeChild(document.getElementsByClassName('parent1')[0]);

//Add a new div element between children
const parent2 = document.getElementsByClassName('parent2')[0];
let newDiv = document.createElement('div');
newDiv.className = 'parent1';
parent2.insertBefore(newDiv, parent2.querySelector('.child2'));

Answer №3

If you want to successfully implement this solution, my recommendation would be to eliminate the div.parent2 that surrounds the child classes. Therefore, your revised code should look like this:

<div class="container parent">
 <div clas="parent1"></div>
 <div class="child1"></div>
 <div class="child2></div>
</div>

After making this adjustment, you can utilize flexbox for achieving the desired layout.

.parent{display: flex};
.child1{order:1}
.parent1{order:2}

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

Utilizing the spread operator to map an array within another array

Exploring the spread operator inside an array to map values from another array has led to unexpected behavior. When attempting to return 2 objects using map within the array, only the last object is being returned. Below is the code snippet: const cats = [ ...

Create a Vue3 Component without attaching it to the DOM

Let's consider creating a Vue3 component in the following way: import { defineComponent } from "vue"; var instance = defineComponent({ computed:{ message() { return 'Hello world' } } }) To instantiate it and ...

Navigate to the initial visible element on the specified webpage via the page hash link

In my handlebars HTML template, I have a partial view that includes different pieces of content for desktop and mobile. I use different CSS classes to hide and show these elements accordingly. <div class='hideOnMobile showOnDesktop'> < ...

WebRTC error encountered: Unable to add ICE candidate to 'RTCPeerConnection'

Encountering a specific error in the browser console while working on a project involving p2p video chat. The error message is Error: Failed to execute 'addIceCandidate' on 'RTCPeerConnection': The ICE candidate could not be added.. Int ...

Jquery not functioning properly for show and hide feature

I'm new to using Jquery and JqueryUI. I have a div named front, which I want to initially display on window load and then hide it by sliding after a delay of 5500 milliseconds. However, I'm encountering errors in the jquery.min.js file. The HTML ...

What steps should I take to ensure that this accordion is responsive?

I am currently working on an accordion design and trying to figure out how to make it full width and responsive. I have experimented with various width and display attributes, but I haven't been able to achieve the desired result yet. If you'd l ...

[Vue alert]: "Maximum" property or method is not declared in the instance but is being referenced during the rendering process

Here is my custom Vue component: Vue.component("product-list", { props: ["products", "maximum-price"], template: ` <div> <div class="row d-flex mb-3 align-items-center p-3 rounded-3 animate__animate ...

What's wrong with the current longitude and latitude bounding box algorithm used for geolocation searches?

I am currently working on a piece of code that calculates a bounding box for a specific location to search for user profiles within a given radius. The code is mostly functional, but I am encountering a slight distortion in the final values. When I input 5 ...

Using JavaScript, divide a string containing elements of unknown length that may be adjacent based on their type

If I have a string representing an SVG path like: "M72 0v754h405v-86h-311v-211h302v-86h-302v-285h311v-86h-405z" My goal is to transform it into an array where each element consists of either a letter or a positive/negative number. For example: [ ...

Extracting Parameters using JQuery's load Method

On a webpage, I am attempting to load a jsp page (another.jsp) within a div element while passing parameters. $("#div").load('another.jsp?a=1&b=2'); Despite trying various methods multiple times, I have not been able to get the desired outc ...

The call stack limit has been exceeded due to the combination of Node, Express, Angular, and Angular-route

Embarking on a new SPA journey, my tech stack includes: Back-end: NodeJS + Express Front-end: Angular + Angular-route. Twitter Bootstrap Underscore Having followed many tutorials with similar stacks, my project files are structured as follows: pac ...

Adjusting the width of a nested Angular custom directive within an *ngIf statement to an absolute value

I'm struggling with a custom angular directive that I only want to display conditionally using ng-if. The directive contains HTML elements, one of which is positioned absolutely. My goal is to make the absolute element's width match the root wid ...

What is the best way to troubleshoot a $http asynchronous request?

Is there a way to pause the program execution in AngularJS $http call after receiving a successful response? I've attempted to set a breakpoint at that point, but it does not halt the execution. I've also tried using the debugger directive, but ...

Learn how to stream videos using the YouTube Player API's loadPlaylist feature

Is there a way to make the next video play automatically using the loadPlaylist option? I've tried implementing this code but unfortunately, it doesn't work and the video won't play: <div id="player"></div> <script> var ...

Are you in need of a BISON middleware solution for socket.io encoding and decoding?

Is there a method to manipulate the data transmitted by socket.io just before it is sent or received? I was considering implementing something like an express middleware. This way, I could encode the data after the normal .emit() call and before the socket ...

JavaScript: Retrieve the Number of Subscribers on the BroadcastChannel

Is there a way to check if a Broadcast channel exists and see how many subscribers it has? We have a product link, and some Chrome tabs are subscribed to a Broadcast channel. We want to determine the number of listeners. const bc = new window.BroadcastCha ...

aligning buttons vertically within a dual-column design

I'm trying to create a two-column layout, where the left column contains a vertically centered button and the right column is text only. Although I have successfully implemented the two-column layout, I am facing difficulty centering the button due t ...

Display live data directly from a specific XML tag on a webpage

My project involves working with a local XML file that is being constantly updated by a third party. I am looking to create a web page that can dynamically read and display a specific XML tag without requiring the page to be refreshed. Additionally, I woul ...

The for loop does not cycle through every element

I'm working on a class project that involves creating custom HTML tags with JavaScript. I have a for loop set up to iterate over each use of the tag, but for some reason, it only seems to loop over every other tag. I'm specifically trying to crea ...

Inability to assign a value to an @input within an Angular project

I recently started using Angular and I'm currently trying to declare an input. Specifically, I need the input to be a number rather than a string in an object within an array. However, I'm encountering difficulties and I can't figure out wha ...