Encase the entire section following cloning with JQuery

Make sure to check out the jsfiddle demo linked below before proceeding:

JSFIDDLE

I need to transform the original structure as shown below:

<div class="out">
 <a>im here</a>
 <a>to save</a>
 <a>our</a>
 <a>country</a>
</div>

into

<div class="newout">
    <ul>
        <li class="haha">
            <a>im here</a>
            <span><a>im here</a></span>
        </li>
        <li class="haha">
            <a>to save</a>
            <span><a>to save</a></span>
        </li>
        <li class="haha">
            <a>our</a>
            <span><a>our</a></span>
        </li>
        <li class="haha">
            <a>country</a>
            <span><a>country</a></span>
        </li>
    </ul>
</div>

This involves the following steps:

  • 1. Clone the a tags
  • 2. Wrap them with span tags
  • 3. Append them to the previous a tags
  • 4. Wrap the previous tags in a li tag and add a class
  • 5. Wrap all the elements in a ul tag

I am struggling with implementing STEP 4 using JQuery. I am unsure of how to select the tags and add the necessary wrapping element.

Any help would be greatly appreciated!

Answer №1

Attempt

$(document).ready(function() {

    var $ct = $('.out').removeClass('out').addClass('newout');
    var $ul = $('<ul />').appendTo($ct);
    $ct.children('a').each(function(){
        var $this = $(this);
        $this.wrap('<li class="haha" />');
        $('<span />').append($this.clone()).insertAfter($this);
        $this.parent().appendTo($ul)
    })

});

Demo: Fiddle

Alternatively

$(document).ready(function () {    
    var $ct = $('.out').removeClass('out').addClass('newout');
    var $ul = $('<ul />').appendTo($ct);
    $ct.children('a').each(function () {
        var $this = $(this);
        $('<li />', {
            'class': 'haha'
        }).append(this).append($('<span />').append($this.clone())).appendTo($ul)
    })
});

Demo: Fiddle

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

Setting constraints for table size with min-width and max-height

I have a coding dilemma involving the min-width and max-height properties in my table. The issue arises when I try to set these properties on the td element – they are being ignored by the browser. If I nest a div with the properties inside a td, the con ...

Using AJAX to invoke a REST service endpoint

I'm currently implementing a REST service call using AJAX. $(document).ready(function () { var xmml = getXmlLoginRequest(); var wsdlURL = getWSDL('search'); $.ajax({ type: "POST", url: wsdlURL ...

The async/await feature is not pausing for the completion of the async.map function call

I'm encountering an issue in my Node.js app where I need to gather and format data using a helper function for an API endpoint. The problem arises when trying to loop through an array and make asynchronous calls to the database for each entry. Despite ...

What benefits come from employing jQuery for data storage techniques?

After learning more about jQuery data storage, I have a question. Is there any advantage to using either of these methods: $('#editCity').data('href', "xx"); var a = $('#editCity').data('href'); or $('#edit ...

What is the best way to assign multiple values to certain elements within an array?

I have an array that looks like this: items = { item1: 10, item2: 5, item3: 7, item4: 3, }; I am looking to include additional details in this array, for example: items = { item1: 10 {available: true}, ...

The column headers are not being shown in Jquery datatables

This particular question is related to the thread found here. Nevertheless, my situation differs slightly. I am looking to implement the same datatables example from the aforementioned question, which can be accessed here. In that example, you must provide ...

Executing Node.js child processes: streaming stdout to console as it happens and running the processes one after the other

Details node: v9.4.0 I am looking for a solution to execute external commands sequentially while monitoring the stdout in real-time. The code snippet below demonstrates my attempt to retrieve all test cases from ./test/ and then running them one after ...

What is the best way to transfer information from a server running Express.js to a client using React.js?

When using Express.js, I have the ability to send an HTML file that includes a React component. app.get('/index', function(req, res) { res.sendFile(path.join(__dirname + '/src/index.html')); }); Suppose I want to send a uniqu ...

What is the process for executing JavaScript and triggering a postback?

How can I create an 'Add to Favorites' button that changes the image in JavaScript and then performs a postback on an ASP.NET page? aspx <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-t ...

Generate unique identifiers to rotate images dynamically on the webpage

My goal is to rotate every image on a page, and while this works with a single image, it only rotates the first one since each ID needs to be unique. I need to find a way to dynamically increment the IDs as they are encountered on the page. Below is what I ...

Creating the Apk file for your sencha touch application

Hello there! I'm diving into the world of Sencha Touch as a new user. After installing all the required tools and SDK, I successfully set up the demo example that came with project creation via command line. Now, I'm eager to generate the APK fil ...

Encountering an Error in Node.js When Defining Routes Using Variable Routes

Here is the code snippet from my App.js file- var routes = require('./routes'); app.get('/', routes.index); //var abt = require('./routes/about'); app.get('/about', routes.about); This is the code from my index.j ...

I'm having some unexpected reflections with the threejs cube camera

I'm currently experimenting with creating an object that reflects on all sides. Although I've made progress, I seem to be encountering some issues. At certain angles, I can only see partial reflections and the scale of the reflection is much larg ...

How can we universally detect and resolve the user's language within a React/Next.js application using an Apollo client HOC?

Currently, I am developing an I18n module utilizing the Next.js framework (v5). The challenge I am facing is determining the user's default language universally in order to display the UI in that language. While it is relatively simple to resolve th ...

Tips for sorting through a multi-dimensional array of objects

I'm looking to filter this array based on the attributevalue. For example, if I search for blue color, I want all shirts in blue color to be displayed. And then if I further search for cotton fabric in blue color, I want all cotton products with blue ...

The div element is not extending all the way to the left side of the browser window

I'm having trouble positioning a menu at the top of my webpage following a tutorial. The menu icon doesn't seem to reach all the way to the left side of the page. Despite multiple attempts to adjust the margin and padding settings, I can't ...

Is there a way for me to display information from a secondary child component by simply clicking a button on the main component instance?

Consider a scenario where there is a main instance, a child component named "movie-card," and another child component within "movie-card" called "link-btn." The objective is to create a selector that loops through the "link-btn" component using v-for. Addi ...

Sending information from the backend to the frontend using Node.js and Express

I am seeking advice on the most effective method for achieving a specific task. In my Node.Js / Express application, there is a point where I need to send data to the backend and receive a certain value back to the front end. Typically, this can be accomp ...

What could be causing my CSS background image to not display properly?

For some reason, I can't figure out why it's just displaying a blank screen. This is what I'm seeing: https://i.sstatic.net/0gDIK.png Here is the structure of my files: https://i.sstatic.net/GDToF.png The CSS code looks like this: *{ ...

ES6 promises: the art of connecting functions with parameters

Looking for a way to chain functions with delays? Here is an example of what I have tried: Promise.resolve() .then(setKeyframe('keyframe-0')) .then(delay(3000)) .then(setKeyframe('keyframe-1')) .then(delay(3000)) .then(setKeyframe(&apo ...