Rearranging anchor tag order with the power of JQuery

Imagine I have five anchor tags

<a id = "A" class = "Home">Home</a>
<a id = "B" class = "Maps">Maps</a>
<a id = "C" class = "Plans">Plans</a>
<a id = "D" class = "Community">Community</a>
<a id = "E" class = "Comments">Comments</a>

I want to rearrange the elements in any order like this:

<a id = "E" class = "Comments">Comments</a>
<a id = "D" class = "Community">Community</a>
<a id = "C" class = "Plans">Plans</a>
<a id = "A" class = "Home">Home</a>
<a id = "B" class = "Maps">Maps</a>

Using jQuery, I thought of using detach() and then after(), but I'm having trouble implementing them correctly.

Here's what I attempted:

var b = document.getElementById("B");
var c = document.getElementById("C");
$("a").detach("#B");
$("c").after(b);

Let me know if you can help. Thank you!

Answer №1

Why not consider utilizing the Flexbox order property instead of manually rearranging elements?

$("#A").css("order", "4");
$("#B").css("order", "5");
$("#C").css("order", "3");
$("#D").css("order", "2");
$("#E").css("order", "1");
div {
  display: flex;
}
div a {
  padding: 10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div>
  <a id = "A" class = "Home">Home</a>
  <a id = "B" class = "Maps">Maps</a>
  <a id = "C" class = "Plans">Plans</a>
  <a id = "D" class = "Community">Community</a>
  <a id = "E" class = "Comments">Comments</a>
</div>

Answer №2

Illustrating a straightforward example:

$('.moveA').click(function() {
  $('#A').insertAfter($('#E'));
});
a {
display: block;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/bulma/0.4.2/css/bulma.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a id = "A" class = "Home button is-success">Home</a>
<a id = "B" class = "Maps button is-success">Maps</a>
<a id = "C" class = "Plans button is-success">Plans</a>
<a id = "D" class = "Community button is-success">Community</a>
<a id = "E" class = "Comments button is-success">Comments</a>
<a class="moveA button is-success">move link A to bottom</a>

Answer №3

To switch the position of two elements identified as "D" and "E", use the following code:

$("#D").insertAfter("#E");

Answer №4

Here is a suggestion for a method you might find helpful: Your HTML code can be structured like this:

<div id="container">
    <a id="A" class="Home">Home</a>
    <a id="B" class="Maps">Maps</a>
    <a id="C" class="Plans">Plans</a>
    <a id="D" class="Community">Community</a>
    <a id="E" class="Comments">Comments</a>
</div>

Your JavaScript method can be implemented as follows:

 var container = $('#container');
 function changeOrder(positions){
    positions = positions.split(',');
    for(var i = 0; i < positions.length; i++){
        container.append($('#'+positions[i]));
        container.append(' ');
    }
 }

By calling the method with the desired order, you can easily re-order the elements anytime:

changeOrder("C,D,E,B,A");

I hope you find this solution helpful.

Answer №5

Give this a try! Simply update the variable $link_order with your preferred element order

$link_order = "BCEDA"; //Define the desired order of links

for($i = 0; $i < $link_order.length; $i++){
  $element = "#" + $link_order[$i];
  $_temp = $($element); //Store the element temporarily
  $($element).remove(); //Remove the element from its current position
  $("#links").append($_temp); //Add back the element in the correct order
  $("#links").append(" "); //Add some space between elements
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="links">
  <a id = "A" class = "Home">Home</a>
  <a id = "B" class = "Maps">Maps</a>
  <a id = "C" class = "Plans">Plans</a>
  <a id = "D" class = "Community">Community</a>
  <a id = "E" class = "Comments">Comments</a>
</div>

Answer №6

Simply utilizing the .insertAfter function will relocate it to your desired location.

Moreover, if you are curious about why the spacing has disappeared, it is due to:

Tackling the Spacing Issue Between Inline Block Elements

A arrangement of inline-block elements styled in a typical HTML format will exhibit spaces between them.

Reference: https://css-tricks.com/fighting-the-space-between-inline-block-elements/

Illustrated below:

body {
  font-family: sans-serif;
  font-size: 16px;
  padding: 5px 20px;
}

ul {
  list-style: none
}

li {
  background: slategrey;
  display: inline-block;
  /* inline block hack for IE 6&7 */
  zoom: 1;
  *display: inline;
  padding: 4px;
  color: white
}

ul.white-space-fix li {
  margin-right: -4px;
}

ul.zero-size {
  font-size: 0px;
}
ul.zero-size li {
  font-size: 16px;
}

ul.flexbox {
  display: -webkit-box;      /* OLD - iOS 6-, Safari 3.1-6 */
  display: -moz-box;         /* OLD - Firefox 19- (buggy but mostly works) */
  display: -ms-flexbox;      /* TWEENER - IE 10 */
  display: -webkit-flex;     /* NEW - Chrome */
  display: flex;             /* NEW, Spec - Opera 12.1, Firefox 20+ */
}
<h1>Inline-block / white-space bug</h1>
original...
<ul>
  <li>one</li>
  <li>two</li>
  <li>three</li>
</ul>

fixed by funky code formatting...
<ul>
  <li>
   one</li><li>
   two</li><li>
   three</li>
</ul>

fixed by adding html comments...
<ul>
  <li>one</li><!--
  --><li>two</li><!--
  --><li>three</li>
</ul>

$('#C').insertAfter($('#E'));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<a id="A" class="Home">Home</a><a id="B" class="Maps">Maps</a><a id="C" class="Plans">Plans</a><a id="D" class="Community">Community</a><a id="E" class="Comments">Comments</a>

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

Exploring the world of form interactions in Angular: A guide to creating dynamic element communication

I have created a form using Angular, and I want to display a specific value in my input field when an element is selected from the dropdown. Additionally, since the values in the dropdown are fetched from a server, I want to show a corresponding label for ...

The art of placing images using CSS

I'm having trouble aligning the images into two rows of three, with the news section on the right side below the navigation bar. I've tried different methods but can't seem to get it right. Both the image and link should be clickable, but I& ...

Storing user responses on a webpage

I am feeling quite lost in my design and I need some help from a talented programmer who can guide me through this realm which is not exactly my area of expertise. My Current Assets Page - form.html <div style="text-align:left"> <form ...

Is it possible to manually activate a dropdown event using pure JavaScript?

I am attempting to manually trigger a dropdown event using JavaScript. Below is the function where I am trying to achieve this. I have successfully halted the initial event that occurs and now I need to initiate a dropdown event. stopNavigationTriggerDrop ...

The imported font used in Firefox is displaying with a striking underline text-decoration

I am currently using the Cardiff font in a project and attempting to apply the style text-decoration:underline to it. While this works perfectly in Chrome (Version 35.0.1916.114), in Firefox (Version. 29.0.1) the underline appears to be crossing through t ...

learning how to combine two json arrays of objects and showcase them in a react component

What is the best way to combine this data and present it in a table with a map using React? The text will be in the first column and the count in the second. const handleSubmit = async (event) => { event.preventDefault(); let URL1 = " ...

Employing Bootstrap, incorporate a vertical divider in the center to split three icons on the left and three icons on the right, all while ensuring the design remains responsive

I have been struggling with a layout issue for the past couple of days and I am in need of assistance from someone who can help me. Unfortunately, I am unable to upload an image here as I am new and do not yet have enough reputation points. The Layout Str ...

Unable to submit form upon clicking radio button in .NET Core

Trying to submit a form by clicking on a radio button. The JQuery code used for submitting the form: Form: @for (var item = 0; item < Model.Count(); item++) { <form id="myform" action="xx" controller="xxx" method="post"> ...

Updating Django database records with ajax

I'm currently working on a feature that involves filtering table data and updating the table using ajax. Here's what I have so far: Filter Form: <form id="search" method="POST" action="{% url 'article-filter' %}"> <input ...

Enabling JsTree Checkbox selection according to unique data-id values

I am seeking assistance to automatically check unchecked checkboxes in a jstree based on their data-id values. When the dropdown selection changes, I want to trigger this action. Below are details of my controller and AJAX method. View of my jstree is sho ...

Using `href="#"` may not function as expected when it is generated by a PHP AJAX function

I am facing an issue with loading html content into a div after the page has loaded using an ajax call. The setup involves a php function fetching data from the database and echoing it as html code to be placed inside the specified div. Here is my current ...

An issue encountered while implementing a post method with fetch and Express

I'm just starting out, so I hope my question isn't too basic. My goal is to send a longitude and latitude from client-side JavaScript to a Node.js server using Fetch and Express.js. Below is the HTML code snippet: <!DOCTYPE html> <html ...

JavaScript array contains duplicate values

I have developed a custom Asp.Net user control. To keep things simple, I have omitted some of the HTML code. <asp:Panel ID="PanelInputControl" runat="server" CssClass="input-control input-period"> <div ID="InputWrapperMonth" runat="server" c ...

Creating a layout in jQuery Mobile with two HTML <input type="button"> elements positioned side by side and each taking up 50% of the screen

After trying numerous strategies, I am still struggling to place two buttons next to each other evenly: <input type="button" value="This week's Schedule" onclick= 'window.location.href = dic[current_sunday]' /> <input type="button ...

Is there a subsequent event that follows the data-rel attribute with the value of 'back'?

How can I determine the value of window.location.hash when a user navigates back using a button with data-rel='back'? Is there a specific event that triggers at this moment? ...

Is it possible for parameters to still be filled even when they start off empty

Currently, I am enrolled in a javascript course and struggling to comprehend how the parameter in my example below is populated with the "correct stuff" without actually calling the function with a corresponding element? success: function(result) { ...

Fancybox 2 - CSS styles vanish when using Ajax request

I have a fancybox2 with static dummy content that has styling applied. It works fine, but now I need to load dynamic content via ajax. However, when I make the ajax call, the required content loads but loses all css styling, most likely due to changes in t ...

Implementing Othello Minimax Algorithm in React.js Yields Unsuccessful Results

I need assistance with a recurring issue where the AI player consistently plays the first available move it encounters. My objective was to implement an AI using the Minimax Algorithm, but I'm facing challenges in achieving the desired functionality. ...

Tips for identifying and handling a 400 bad request error in an HTTP response within an Angular 2 application

I attempted to handle the error 400 bad request in this manner: catch((error: any) => { if (error.status === 500) { return Observable.throw(new Error(error.status)); } else if (error.status === 400) { console.log( 'err ...

Show a table with rows that display an array from a JSON object using JavaScript

My current code includes JSON data that I need to display in table rows, but I'm struggling to understand how to do so effectively. The output I am currently seeing is all the rows from the array stacked in one row instead of five separate rows as in ...