How can JavaScript be used to rearrange the placement of DOM elements?

<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>
    <div class="boxes">
        <div class="red" style="width: 300px; height: 300px; color: red"></div>
        <div class="blue" style="width: 300px; height: 300px; color: blue"></div>
    </div>

</body>
</html>
<style>
 .boxes{display:flex; flex-direction:row;}
</style>

Is it possible to swap the positions of div.blue and div.red using CSS or JavaScript?

Answer №1

No JavaScript necessary to arrange the elements.

Check if this meets your requirements:

.boxes {
  display: flex;
}

.blue {
  order: 1;
}

.red {
  order: 2;
}
<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>
    <div class="boxes">
        <div class="red" style="width: 300px; height: 300px; background: red"></div>
        <div class="blue" style="width: 300px; height: 300px; background: blue"></div>
    </div>

</body>
</html>

Answer №2

You have the ability to achieve this using the CSS flex property. Simply adjust the boxes element's flex-direction to row-reverse.

.boxes {
  display: flex;
  flex-direction: row-reverse;
}
<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>
    <div class="boxes">
        <div class="red" style="width: 300px; height: 300px; background: red"></div>
        <div class="blue" style="width: 300px; height: 300px; background: blue"></div>
    </div>

</body>
</html>

Note

If you prefer to have the two boxes aligned vertically, then opt for flex-direction: column-reverse; instead of row-reverse.

Answer №3

Access the parent element with the class '.boxes', retrieve the indexes of its child elements, and then perform a swap:

parentNode.children[1].parentNode.insertBefore(parentNode.children[1], parentNode.children[0]);

Answer №4

Not the most elegant code.


    const divElement = document.querySelector(".container").querySelector(".red");
    divElement.remove();
    
    const blueElement = document.querySelector(".container").querySelector(".blue");
    blueElement.remove();

    const container = document.querySelector(".container");
    container.appendChild(blueElement);
    container.appendChild(divElement);

Answer №5

Feel free to modify this as you wish.

document.querySelector(".red").addEventListener("mouseover",()=>{
document.querySelector(".red").style.background="blue"
document.querySelector(".blue").style.background="red"

})
<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>
    <div class="boxes">
        <div class="red" style="width: 300px; height: 300px; background: red"></div>
        <div class="blue" style="width: 300px; height: 300px; background: blue"></div>
    </div>

</body>
</html>
<style>
 .boxes{display:flex; flex-direction:row;}
</style>

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

Tips for ensuring an element stays anchored at the bottom even when the keyboard is displayed

I recently encountered a situation on one of my pages where an element positioned at the bottom using absolute positioning was causing issues when the keyboard was opened, as it would move to the middle of the page unexpectedly. While this may seem like a ...

JavaScript scroll event not firing

I have searched multiple questions on SO to avoid duplication, but none of the solutions worked for me. My goal is to toggle the visibility of a button based on scroll position. I tried creating a scroll event listener to trigger a function that checks th ...

"Ensuring Your SVG Icon is Perfectly Centered: A Step

My SVG icon is currently aligned to the left, but I want to center it. I tried using the following code, but it doesn't seem to be working: .parent{ display: flex; align-items: center; font-size: 13px; } span{ margin-right:10px } When I look at the S ...

Encountering an undefined json array when making an AJAX request

There have been numerous questions on this topic, but none of the specific solutions seemed to apply to my situation. So, I apologize if this is a duplicate query. I am currently working on fetching data from an SQL database using a PHP file that passes t ...

Tips on eliminating overlapping strokes

I'm having trouble with drawing an array of circles that are meant to intersect a series of lines. The issue I face is that if the circles overlap, a stroke appears underneath them which I want to remove. Does anyone have any suggestions on how to el ...

Ensuring type signatures are maintained when wrapping Vue computed properties and methods within the Vue.extend constructor

Currently, I am trying to encapsulate all of my defined methods and computed properties within a function that tracks their execution time. I aim to keep the IntelliSense predictions intact, which are based on the type signature of Vue.extend({... Howeve ...

Styling a webpage with a two-row layout using just CSS

I am looking to design a 2-row layout for a webpage where one row will contain filters and the other row will display results. The layout should meet the following criteria: The page height should not exceed 100% The first row's height will vary bas ...

Display the map using the fancybox feature

I have added fancybox to my view. When I try to open it, I want to display a map on it. Below is the div for fancybox: <div id="markers_map" style="display:none"> <div id="map_screen"> <div class="clear"></div> </div&g ...

I need to access the link_id value from this specific actionid and then execute the corresponding function within the Ionic framework

I have a JavaScript code in my TypeScript file. It retrieves the attribute from a span element when it is clicked. I want to store this attribute's value in a TypeScript variable and then call a TypeScript function. Take a look at my ngOnInit method, ...

What will be provided as the outcome?

I have recently started learning express.js. The following code snippet is taken from the router library of express.js. var proto = module.exports = function(options) { options = options || {}; function router(req, res, next) { router.handle(req, ...

After triggering an action, I am eager to make a selection from the store

To accomplish my task, I must first select from the store and verify if there is no data available. If no data is found, I need to dispatch an action and then re-select from the store once again. Here is the code snippet that I am currently using: t ...

Create distinct 4-digit codes using a random and innovative method, without resorting to brute force techniques

I am working on developing an application that requires generating random and unique 4-digit codes. The range of possible codes is from 0000 to 9999, but each day the list is cleared, and I only need a few hundred new codes per day. This means it's fe ...

Combining React state value with an HTML tag would be a great way

I am facing an issue while trying to concatenate the previous value with new data fetched from an API using a loop. Instead of getting the desired output, I see something like this: [object Object][object Object],[object Object][object Object] Here is ...

How to use AJAX to retrieve the text content of an HTML option value?

I have a script that displays a list of values, which I want to write: <option th:each = "iName : ${iNames}" th:value = "${iName}" th:text = "${iName}" th:selected="${selectedIName == iName}" In addition, I have the function setSelectedName in my .j ...

In CSS, use the p tag to make sure content fills the available space when the browser is resized beyond a certain point

Before I begin, I must clarify that I do not specialize in front-end development and my expertise in UI/UX is limited. With that said, here is my query: I have a div containing p tags. I wish for this div to have a width: 700px when the browser window is ...

What are the best techniques for styling a SELECT box with HTML and CSS?

I've received a form from a talented designer which includes SELECT inputs designed in a unique manner. Despite my attempts to add paddings, adjust backgrounds, I'm unable to replicate the exact appearance of the select box shown in the image. ...

Cannot locate module using absolute paths in React Native with Typescript

I recently initiated a new project and am currently in the process of setting up an absolute path by referencing this informative article: https://medium.com/geekculture/making-life-easier-with-... Despite closely following the steps outlined, I'm en ...

Expressing the relationship between API endpoints in a nested structure

I'm currently working on a REST API using expressjs. There are two api endpoints that I have defined: router.get('/probe/:id', function() {}); router.get('/:id', function() {}); However, I am facing an issue where calling the fir ...

AngularJS is failing to recognize the onload event when loading a URL

I am currently working with the AngularJS Framework and I have encountered an issue. My directive only seems to work when the window is fully loaded. screensCreators.directive('createscreen', function () { return { restrict: "A", ...

Using Regular Expressions in an ExpressJS Router

When working with ExpressJS, is there a way to combine the following routes into one using RegEx? app.get(/^\/blog(?:\/p(\/\d+)?)?$/, blog.list); ...