Duplicate multiple "li" elements using jQuery and place them in a designated position within the ul element, rather than at the end

I am currently working on developing a dynamic pagination bar. This pagination bar will dynamically clone the "li" elements based on a number received from an external webservice.

Here is the structure of my pagination element:

<ul class="pagination">
            <li class="pagePrevious" name="previous">
                <a href="#" aria-label="Previous"> <span aria-hidden="true">«</span> </a>
            </li>

            <li class="page" name="1"><a href="#" class="is-active">1</a></li>

            <li class="pageNext" name="next">
                <a href="#" aria-label="Next"> <span aria-hidden="true">»</span> </a>
            </li>
</ul>

You may notice that the first and last "li" elements inside the Ul are static buttons for previous and next, which are not cloned and remain present at all times.

My cloning function involves selecting the second to last child of the "li" elements, cloning it with a new incremental id, and then inserting it into the ul.

This is what my function looks like:

createPagination: function (nb) {
            var lastLI = $('.pagination li').last().prev();
            var num = lastLI.attr('name');

            for (var i = num; i <= nb ; i++) {
                if (i != num) {
                    var cloned = lastLI.clone().attr('name', i);
                    $(cloned).find('a').text(i);
                    $('ul').append(cloned);
                }
            }
        }

My issue is figuring out how to always append the cloned "li" before the last "li" of the next button element. Any suggestions on how to achieve this without changing the class attribute names?

Any ideas or tips would be greatly appreciated!

Answer №1

Implement the .before() method to insert content directly before another element.

createPagination: function (nb) {
    var nextLI = $('pagination .pageNext');
    var lastLI = nextLI.prev();
    var num = lastLI.attr('name');

    for (var i = num+1; i <= nb ; i++) {
        var cloned = lastLI.clone().attr('name', i);
        cloned.find('a').text(i);
        nextLI.before(cloned);
    }
}

By the way, there is no need to add $(cloned), as cloned is already a jQuery object. Also, if you initiate the for loop at num+1, there's no requirement to check if (i != num).

Answer №2

One way to solve this problem is by utilizing the insertBefore function instead of append:

let lastItem = $('.pagination li').last().prev();
            let nextItem= $('.pagination li').last();
            let number = lastItem.attr('value');

            for (let i = number; i <= totalItems ; i++) {
                if (i !== number) {
                    let clonedItem = lastItem.clone().attr('value', i);
                    $(clonedItem).find('a').text(i);
                    clonedItem.insertBefore(nextItem);
                    clonedItem.removeClass("is-selected")
                }
            }

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

Encountering 'Unacceptable' error message when attempting to retrieve response via AJAX in the SPRING

I'm encountering an issue with my code where I am trying to retrieve a JSON array response from a controller class. Whenever I send a request from JavaScript, I receive a "Not Acceptable" error. Can someone please assist me in identifying the bug in m ...

What is causing the issue of the page overflowing in both the x and y axis while also failing to center vertically?

I've been trying to align the <H4> styled component to the center of the page using flex-box, but it's not working as expected. I also attempted using margin:0 auto, but that only aligned the H4 horizontally. Additionally, I'm investi ...

How can I ascertain which ajax request is on the verge of being executed?

In my current project, I have implemented multiple ajax calls that execute periodically using the timeInterval() method. To indicate loading or refreshing effects, I'm utilizing the following code snippet: jQuery(document).ajaxStart(function(){ ...

Responsive navigation menu featuring dynamic dropdown menus using HTML and CSS

Looking to design a responsive HTML and CSS navigation menu with multiple dropdown menus? You're in the right place. I've scoured countless YouTube videos, but haven't quite found the perfect template for a two-part navigation menu that tic ...

NodeJS npm module installed globally is unable to run the main/bin JavaScript file using node command

Here is an example of my package.json: { "name": "example-module", "version": "1.0.0", "bin": "./bin/example-module.js", "main": "./bin/example-module.js", "description": "Example module description", "homepage": "http://my.home.page.com", " ...

Convert an HTML webpage into a JSON format that represents the structure of the DOM tree

I am having an index.html file with multiple div tags inside it. I am attempting to retrieve content from all the div tags on the page, but currently, I am only able to fetch the content from the first div tag. What I actually need is the content from all ...

Iterating using a for loop within different functions

I am facing an issue with this project. I am planning to create a function that calculates from two different `for()` loops. The reason behind having 2 separate functions for calculation is because the data used in the calculations are fetched from differe ...

fixed footer with fixed height on parent container

I have successfully implemented a sticky footer on my web pages by following specific instructions. http://css-tricks.com/snippets/css/sticky-footer/ The recommended approach includes using min-height:100% and not specifying the height property. .page-w ...

`How can I use lodash to filter an array based on any matching value?`

I have a collection of objects and I need to search for instances where certain properties match specific values. Here is an example array: let arr = [ { a: 'foo', b: 'bar' }, { a: 'bar', ...

What is the best approach to animating a specified quantity of divs with CSS and javascript?

How neat is this code snippet: <div class="container"> <div class="box fade-in one"> look at me fade in </div> <div class="box fade-in two"> Oh hi! i can fade too! </div> <div class="box fade-in three"& ...

The mixin animation received 2 arguments, even though it only accepts 1

Below is the sass code snippet, @include animation(swayb $speed ease infinite 3s, reset 1s ease forwards 5s); When I try watching using compass watch on my Ubuntu machine, it triggers an error, (Line 2500 of _includes/_common.scss: Mixin animation tak ...

The onClick function for a button is not functioning properly when using the useToggle hook

When the button is clicked, it toggles a value. Depending on this value, the button will display one icon or another. Here is the code snippet: export const useToggle = (initialState = false) => { const [state, setState] = useState(initialState); c ...

Tips for continuously randomizing colors in p5.js

I recently began exploring p5.js and I have a query regarding color randomization. Currently, it seems that the color only changes randomly when I restart the code. Is there a way to trigger this randomization every time the mouse is clicked? Below is the ...

"Using html_attr with the attribute "href" does not return any value in the rvest package

My objective is to extract the URLs linked with specific CSS elements on a website using rvest. Despite trying various methods, such as using the html_attr function with the 'href' argument, my current script only returns NA values instead of the ...

Unlocking the Power of VueJS Mixins in an External JS Library

I'm currently using a 'commonLibrary.js' in my Vue application. One of the functions in this library that I find particularly useful is: var defaultDecimalRounding=3 function formatNumber(number) { if (isNaN(number.value) == tr ...

How can one execute a function within an HTML attribute value using Angular?

I am currently attempting to use the weatherToFontAwesomeIcon(weatherDescription: string) function directly within the HTML file for this component. My goal is to showcase a specific FontAwesome icon based on the weather response from the API. import { Cur ...

Having trouble with Jquery's Scroll to Div feature?

When I click on the image (class = 'scrollTo'), I want the page to scroll down to the next div (second-container). I've tried searching for a solution but nothing seems to work. Whenever I click, the page just refreshes. Any help would be gr ...

Column alignment issue detected

Can you help me with aligning the data in my column status properly? Whenever I update the data, it doesn't align correctly as shown in the first image. https://i.stack.imgur.com/300Qt.png https://i.stack.imgur.com/4Dcyw.png $('#btn_edit' ...

The custom radio button is not showing up on iOs Safari

My code for custom radio buttons using CSS is as follows: input[type=radio]{ display:none; } .radio-options label::before { content: "\2b24"; color:#e2e2e2; display: inline-block !important; width: 17px; height: 17px; vert ...

What is the standard approach for exchanging localized user interface strings between Microsoft's MVC and JavaScript?

In the process of developing an application that utilizes a dynamic, javascript-based client, I am facing the need for localization. This particular application includes significant UI components that are not generated by Javascript and are instead served ...