Create a duplicate <li> element and animate it using jQuery

Here are the list items:

<ul>
<li>...</li>
<li>...</li>
<li>...</li>
<li>...</li>
<li>...</li>
<li>...</li>
<li>...</li>
<li>...</li>
<li>...</li>
</ul>

Is there a way to extract the second half of this list and place it before the first <li> item?

Answer №1

const unorderedList = $('ul');
const listItems = unorderedList.children('li');

unorderedList.prepend(listItems.slice(Math.round(listItems.length / 2)))

Example: http://jsfiddle.net/8SNGn/

This script first saves the reference to the <ul> element and its child <li> elements using the children()[docs] method.

Then it utilizes the prepend()[docs] method to insert the last li elements at the beginning of the ul.

To select the last half of elements, it divides the total number of li elements in two (rounding up with Math.round() for odd numbers) using the slice()[docs] method.


EDIT:

I noticed that your question contains the term "clone".

Although not explicitly stated, if you wish to clone the last half instead, you can achieve this by utilizing the clone()[docs] method.

const unorderedList = $('ul');
const listItems = unorderedList.find('li');

unorderedList.prepend(listItems.slice(Math.round(listItems.length / 2)).clone())

Example: http://jsfiddle.net/8SNGn/1/

If you prefer rounding down instead, you can substitute Math.floor() for Math.round.

Answer №2

let elements = $("ul li");
elements.filter(function(position) {
    return position >= elements.length / 2;
}).prependTo($("ul")[0]);

This code snippet is expected to function correctly.

Answer №3

let totalItems = $('li').length - 1;

for(let j = 0; j < totalItems/2; j++){
    let $listItem = $('li').eq(totalItems);
    $('ul').prepend($listItem);

}

See it in action here: http://jsfiddle.net/CreativeCoder123/Qw3XY/

Answer №4

Implementing jquery prepend function can be done by visiting this link

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

Utilize Meteor-tabular to effortlessly export data with convenient HTML5 export buttons

Currently, I am utilizing the tabular package to display data from a collection in a table format. However, when attempting to export the data using html5 export buttons with the button (csvhtml5), only the length of data visible in the table is exported, ...

Combining HTML file input with a form submission using a button of type "button", along with jQuery in the context of MVC 2.0 in Asp.net

I have a requirement in MVC 2.0 and ASP.NET where I need to upload multiple files using a partial user control view without submitting the form using an input button. The challenge is to post the form with only a button type of 'button' so that ...

Tips for clearing state when simply refreshing a DataTable on the page

When it comes to a datatable on a page, I am facing a unique challenge. I want the datatable to be refreshed with a clear state (no column order, etc.), but if the page is accessed by pressing the back button, it should retain its state. I have experiment ...

Fetch the user's email address from Auth0 using an asynchronous function

I am trying to load the user's email from Auth0 and store it in a constant. However, I am getting an arrow. I cannot identify the error. Can anyone help me find a solution? const userEmailInfo = async () => { auth0Client = await auth.createClien ...

Amount of information gathered through Ruby Mechanize

agent = Mechanize.new url = "---------------------------" page = agent.get(url) I am curious to find out the amount of data in kilobytes consumed by my internet service provider for fetching this information. Specifically, I would like to determine the s ...

How to display and download a PDF file on a JSP web page

Can anyone help me with a simple trick to solve this question I have? In my project folder, I have 5 PDF files named file1.pdf, file2.pdf, file3.pdf, file4.pdf, and file5.pdf. I want to display these files in 5 rows on my webpage, each row containing VIEW ...

The cancel button for the input type "search" does not appear on Firefox, Internet Explorer, and Edge browsers

.hs-search-field__input { color: #111d33; border-bottom: 3px solid #111d33; appearance: searchfield; -moz-appearance: searchfield; -webkit-appearance: searchfield; -ms-appearance: searchfield; color: #fff; border-radius: 0px ...

Continuously encountering the "Uncaught Error: Bootstrap dropdown requires Popper.js" message despite having already added popper.js to the code

Recently beginning my journey with Angular and Bootstrap, I decided to create a simple "hello world" app. I've included all the necessary libraries, but I encountered an error that has me stuck. Error: Bootstrap dropdown requires Popper.js I' ...

Guide: Creating an AngularJS directive for displaying a jQuery dialog that triggers submission on pressing the Enter button

Looking to create a similar functionality to the jQuery modal form Dialog in my AngularJS app to collect the username from the user. I've tried using the twitter-bootstrap modal and AngularUI dialog, but both are lacking in two key areas: Auto-focu ...

Modify a single parameter of an element in a Map

Imagine I have a map data type exampleMap: Map<string, any> The key in the map is always a string, and the corresponding value is an object. This object might look like this: { name: 'sampleName', age: 30} Now, let's say the user se ...

What is the best way to make this relative path function in JavaScript?

My file structure is organized in the following way: multiple folders a subfolder _includes getStatisticsTable.php _templates StatisticsWrapper.html Within StatisticsWrapper.html, I am using jQuery's .get() method to fetch external data which ...

Guide on developing a dynamic Navbar component on Laravel Mix with Vue Js

As I delve into learning and practicing Vue.js, my goal is to create a component that includes elements like Navbar and Footer within a single view. Initially, I set up an index for the first view but faced an issue with adding the navbar as it did not sho ...

The conditional statements within the resize function may not always be triggered when the conditions are fulfilled

Struggling to trigger a function only once when resizing. The issue is that the conditional statements are not consistently executed every time. Here's the code snippet: var old_width = $(window).width(); $(window).on('resize.3col',functio ...

Tips on transmitting and receiving substantial JSON information

As a newbie in the full-stack development world, I am currently on a quest to find an efficient method for transmitting and retrieving large data between my React front-end and Express back-end while keeping memory usage to a minimum. My project involves b ...

The asynchronous ajax function fails to work properly when setInterval is activated

My issue is that only the initial execution of the updateProgress function happens while waiting for the completion of syncDNS. All subsequent calls made via setInterval remain on hold until syncDNS finishes. Can anyone explain why this is happening? $( ...

The information from the Ajax request does not get properly delivered to the $_POST array

Apologies if this question has been raised before, but none of the responses to other inquiries have provided a solution to my issue. I am currently developing a user login system that utilizes an .ajax() call to my login.php file for user authentication. ...

Transform an item into a map of the item's properties

I am faced with an object containing unknown key/value pairs in this format: myObj = { key_1: value_1, key_2: value_2, key_n: value_n } My goal is to transform it into a dictionary of structured objects like the one below: dictOfStructureObjec ...

Enhance your HTML code using JavaScript (specifically jQuery)

Is there a way for me to transform the following code into a more visually appealing format? <td> <a href="/Test/Page/2">Previous</a> <a href="/Test/Page/1">1</a> <a href="/Test/Page/2">2</a> 3 ...

Getting the Tweets of a Twitter-validated user using node.js

I'm struggling with extracting Tweets from a verified user and could use some assistance. I know it's a broad question, but here's the situation: https://github.com/ttezel/twit provides a way to access tweets from any Twitter account. Howev ...

Implementing a consistent CSS structure for various media sizes

Utilizing CSS grid and Sass, I implement varying grid layouts for different screen sizes (phone, tablet, desktop). However, on certain pages, I desire the same layouts at slightly larger or smaller screens than others. Is there a way to achieve this witho ...