Reposition the element at the bottom of its parent element

I am facing an issue with the HTML structure in my application:

    <div class="work-item">
        <div class="image-container">                
        </div>
        <div class="text-container">
        </div>
    </div>

    <div class="work-item">
        <div class="text-container">                
        </div>
        <div class="image-container">                
        </div>
    </div>

    <div class="work-item">
        <div class="image-container">                
        </div>
        <div class="text-container">
        </div>
    </div>

    <div class="work-item">
        <div class="text-container">                
        </div>
        <div class="image-container">                
        </div>
    </div>

I am attempting to target elements with the text-container class, and if it's the first element under work-item, move it after the div with the image-container class. So that the structure of every div element looks like:

    <div class="work-item">
        <div class="image-container">                
        </div>
        <div class="text-container">
        </div>
    </div>

I initially tried removing it using this code:

$(".work-item .text-container:first-child").remove();

It worked as expected. However, when I attempted to move it with the following code, nothing happened:

$("#work .work-item .text-container:first-child").insertAfter($(this).parent()["last-child"]);

Can anyone help me identify what mistake I might be making here?

Answer №1

Here is a solution for your problem:

$('.text-container').each(function(index, item) {
    var $this = $(item);
    $this.appendTo($this.parent());
});
.work-item{
    margin:20px;  
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="work-item">
    <div class="image-container">img              
    </div>
    <div class="text-container">txt
    </div>
</div>

<div class="work-item">
    <div class="text-container">txt             
    </div>
    <div class="image-container">img           
    </div>
</div>

<div class="work-item">
    <div class="image-container">img        
    </div>
    <div class="text-container">txt
    </div>
</div>

<div class="work-item">
    <div class="text-container">txt             
    </div>
    <div class="image-container">img           
    </div>
</div>

Answer №2

Here's a different approach you can take by storing the parent element in a variable:

let parentElement = $(".work-item .text-container:first-child").parent();

$(".work-item .text-container:first-child").detach().appendTo(parentElement);

Instead of using remove, try using detach to keep the information in memory before appending it back to the parent.

Answer №3

To accomplish your goal, simply utilize the insertAfter method.
You can view my example on JSFiddle.

var text = $('.text-container');
var img = $('.image-container');
text.insertAfter(img);

Answer №4

attempt

$(".job-item .content-section:nth-child(1)").each(function () {
    var element = $(this);
    if (element.next().is($(".visual-section"))) {
         var parentElement = element.parent();
         parentElement.append(element.detach());
    }

});

TRY IT OUT

Answer №5

When it comes to the first element, it could either be ".text-container" or ".image-container".

If the initial element happens to be ".image-container".

$("#work .work-item .text-container:first-child").length == 0;

This means that the first element is incorrect.

Here is my solution:

$(document).ready(function() {
var workItems = $(".work-item");

var len = workItems.length,i = 0,el,first;
for(;i < len; i++){
el = workItems[i];
first = $(el).children().first();
if (first.hasClass("text-container")){
$(el).append(first);
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="work-item">
    <div class="image-container">img              
    </div>
    <div class="text-container">txt
    </div>
</div>

<div class="work-item">
    <div class="text-container">txt             
    </div>
    <div class="image-container">img           
    </div>
</div>

<div class="work-item">
    <div class="image-container">img        
    </div>
    <div class="text-container">txt
    </div>
</div>

<div class="work-item">
    <div class="text-container">txt            
    </div>
    <div class="image-container">img           
    </div>
</div>

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

Creating a Sudoku game board using underscore templates

Currently, I am in the process of constructing a Sudoku board using underscores templating. However, I have hit a roadblock when it comes to tackling the mathematical aspects necessary for deriving the table structure. My approach involves utilizing a 1d ...

Use JavaScript to identify and color the intersecting area of two triangles that overlap on a webpage

I created two triangular divs using HTML and I am utilizing jQuery UI to enable them to be draggable. Now, my goal is to overlap these two triangles and change the color of the overlapping area to a different shade. Here is an example: https://i.sstatic. ...

Can you tell me the distinction between using RemoteWebDriver's executeScript() and Selenium's getEval() for executing

Can you explain the distinction between these two pieces of code: RemoteWebDriver driver = new FirefoxDriver(); Object result = driver.executeScript("somefunction();"); and this: RemoteWebDriver driver = new FirefoxDriver(); Selenium seleniumDriver = ne ...

Serve the JS files in Express separately

I am facing issues with my webapp loading too slowly when using the express.static middleware to serve all my js files. I am considering serving each js file only when needed, such as when serving the html from jade that uses the js file. I have attempted ...

Locate a specific text within a complex array of objects and retrieve the objects that contain the match as

I have an array of objects named input as shown below. Each object in the array contains a property vertical of type string, an array called platformList, and a nested object named radar_metadata. I am looking to implement a search functionality where I c ...

Is it possible to call a REST API in Javascript by passing the username and password as

I have been attempting to use Javascript to call the AwaazDe REST API with a specific username and password, but I'm encountering issues. Below is my code: function authenticateUser(user, password) { var token = user + ":" + password; ...

Create a custom navigation bar using Bootstrap styling

I am currently attempting to create a unique Navigation Bar design using bootstrap Here is the code snippet I am working on: <div class="navbar-header"> <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#b ...

Tips for deleting the displayed URL during a web page print in PHP

Is there a way to remove the URL from a page when printing using PHP? I want to achieve this without requiring my clients to change their browser settings. Any assistance would be greatly appreciated! ...

Adding a unique value to an array using JQuery when it does not already exist

In need of assistance with a function that is supposed to add values to an array if they do not already exist. var category_json = new Array(); $.ajax({ type: 'POST', url: "<?php ech ...

What is the process for modifying the popups associated with a polygon object?

As of now, every time I click on the map, a popup shows up with the name of the country based on a geoJSON file containing multi-polygon lnglat coordinates that outline the borders of each country. This method saves me from manually inputting each country& ...

What is the best way to change an int32 to a float32 in Deeplearn.js?

In December 2017, this code did the job perfectly. However, after updating Deeplearn.js to the latest version, it no longer functions as expected: math.scope(function(keep, track) { var i = track(dl.Array3D.fromPixels(rawImageData, 4)); i = math.multi ...

Retrieve a distinct HTML onclick event using VBA

I need some assistance because I have a major issue that I can’t solve or find help for online. Here is the code I am dealing with: <span class="test taLnk hvrIE6" onclick="ta.trackEventOnPage('Hotel_Review' ,'URL_HOTEL|text|2| ...

Is there a way for me to discover the top trending photos on Instagram today?

Finding information on the Instagram API can be quite challenging due to poor documentation. Is there a method available to discover the most liked Instagram photos by location, such as identifying the top picture liked by Danish users today? Any insight ...

Error: The reference to 'ko' is not defined while loading with jQuery

After numerous attempts, I am still encountering the ReferenceError: ko is not defined issue while trying to load KnockoutJS using jQuery's getScript function. Below is the code snippet I have been testing to see if everything is functioning correctl ...

Unable to fetch permissions for user:email via GitHub API

Currently, I am utilizing node-fetch to fetch an OAuth2 token from an OAuth2 GitHub App. The obtained token allows me to successfully retrieve user information from "https://api.github.com/user". However, I also require the email address, which necessitate ...

How can I address the variations in CSS appearance between Firefox and Google Chrome?

I'm currently working on a table with two cells in each row just for fun. For the first row, I want both cells to display the same picture. To achieve this, I wrote the following CSS: tr:nth-child(1){ background-image:url("cat.jpg"); background-size: ...

The functionality of Express' render/redirect is limited to being triggered only by a submit method within a form

Objective To execute a POST request through a JavaScript method in order to send variable values as parameters. Setup NodeJS Express BodyParser ejs Initial Approach Frontend: <html> <head> <script src='http://ajax.go ...

Using JavaScript's indexOf method with multiple search values

I have a data set that includes various duplicate values ["test234", "test9495", "test234", "test93992", "test234"] I am looking to find the positions of every instance of test234 in the dataset Although ...

Tips for Developing Drag Attribute Directive in Angular 2.0

Currently, I am referencing the Angular documentation to create an attribute directive for drag functionality. However, it seems that the ondrag event is not functioning as expected. Interestingly, the mouseenter and mouseleave events are working fine ac ...

Exploring the use of functions in the setup method of Vue 3

I'm currently working on a simple app and utilizing mock-json-server to mimic http requests. Within my project, I have defined a function designed to retrieve the necessary information: import { ref } from 'vue' const getScores = () => ...