When the li is clicked, replicate it and display it in a separate div

When a list item is clicked, I want to clone it and display it in a separate div. If another list item is clicked, the previously displayed item should be replaced with the newly clicked one.

Below is my code along with a link to the codepen where you can view it: https://codepen.io/AnthonyDavid/pen/xxqmqQY

$('li').click(function() {
  $(this).each(function(i) {
    $("<div class='special'>")
      .append($(this).contents().clone())
      .appendTo('#container');
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div id="container"></div>
<ul>
  <li><a href="">First</a></li>
  <li><div>Second</div></li>
  <li><span>third</span></li>
  <li><h4>Fourth</h4></li>
</ul>

Answer №1

avoid triggering any action when clicking on a

$('li a').click((e)=>{e.preventDefault();});
$('li').click(function() {
  $(this).each(function(i) {
    $("<div class='special'>")
      .append($(this).contents().clone())
      .appendTo('#container');
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div id="container"></div>
<ul>
  <li><a href="">First</a></li>
  <li><div>Second</div></li>
  <li><span>third</span></li>
  <li><h4>Fourth</h4></li>
</ul>

Answer №2

I have implemented a click handler for the anchor tags to prevent page redirection and maintain expected functionality.

Modified the code to handle only one item at a time.

$('li').click(function(event) {
  $(this).each(function(i) {
    var data = $("<div class='special'>")
      .append($(this).contents().clone())
    $('#container').html(data);
  });
});

$('.list-wrapper a').click(function(event){
  event.preventDefault();
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div id="container"></div>
<ul class='list-wrapper'>
  <li><a href="">First</a></li>
  <li><div>Second</div></li>
  <li><span>third</span></li>
  <li><h4>Fourth</h4></li>
</ul>

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

Is it possible to incorporate dynamic variables into the directives of a nested loop? Plus, thoughts on how to properly declare variables in a node.js environment

Question Explanation (Zamka): <----------------------------------------------------------------------------------------------------------> Input Example: 100 500 12 1st Line: represents the left bound (L) 2nd Line: represents the right bound ...

Utilizing _.partial on a single-argument function

Currently, I am in the process of refactoring code within a react.js application. There is an element that utilizes Underscore.js _.partial on a function that already has one argument. Is there any real benefit to doing this? I can see how it works based ...

Tips for implementing a for loop within a Bootstrap-Popover using JavaScript

After spending several days searching for a suitable example to no avail, I decided to bring my specific use case to SO. I currently have three Bootstrap 5 cards. https://i.sstatic.net/zDVOF.png I am looking to create Popovers for each card, with the po ...

How can I align my logo on the website header separately from the menu tabs while keeping them on the same row?

Trying to vertically align a logo and headers' tabs in the same row can be quite challenging, especially when the logo is taller than the tabs. I've attempted different methods, including using padding to manually adjust the alignment, but it&apo ...

JavaScript Update Function for Pointers in Parse.com - Modify a Row with a Pointer

I am currently working with Parse and JavaScript. While I know the ObjectId from the Status_id-class, I am facing a challenge in updating the column in the Question_status-class due to it being of Pointer-type. Can anyone guide me on how to update a Poin ...

Prevent duplicate form submissions when reloading using AJAX and Solve the header modification restriction issue

I've encountered an issue where the form is being resubmitted upon page refresh. While there are solutions available online for this problem, my situation is unique because I'm utilizing ajax to submit the form, resulting in only a section of the ...

Is it not possible to include Infinity as a number in JSON?

Recently, I encountered a frustrating issue that took an incredibly long time to troubleshoot. Through the REPL (NodeJS), I managed to replicate this problem: > o = {}; {} > JSON.stringify(o) '{}' > o.n = 10 10 > JSON.stringify(o) ...

JavaScript allows for the hiding of the Android navigation bar on web apps in Chrome, which includes the virtual back, home screen, and other buttons

In the process of developing a web application, I am aiming to provide users with a fully immersive fullscreen experience. This entails hiding not only the Chrome address bar at the top but also the navigation bar at the bottom (which includes virtual back ...

Scheduled Job unable to complete post request

(I am completely new to the world of JavaScript, node.js, and Heroku so I apologize in advance if my question is not very clear) I recently set up a Heroku node.js application with a scheduled task that should run every hour. The task does run as expecte ...

Stopping autoplay in Swiper as soon as you hover over it

My swiper is set to autoplay, but I want it to stop immediately when hovered over instead of waiting for the transition to finish. Is there a way to interrupt the transition and stop it at the exact point where the cursor hovers? Here is my Swiper config ...

Learn how to use Javascript and ASP.NET to refresh the parent page in Mozilla Firefox browser

The code window.opener.location.reload(); works well in Internet Explorer, but it doesn't refresh the parent page in Mozilla Firefox. Can someone please advise me on how to refresh the parent page in a way that is cross-browser compatible? Here is th ...

You are unable to declare a variable within an AJAX function using jQuery

Struggling to update variables within the AJAX function? For example, if there is a variable declared outside like var myName = "My name is Kenny"; and inside the AJAX function you attempt myName.replace("Kenny", "Earl"); Upon running console.log(myNa ...

Using React to Retrieve Array Data from an API and Implementing Filtering

I have successfully made a call to my API endpoint and passed the token. However, I only need specific details from the response data - specifically, I want to work with the first index in the array that contains fields. My goal is to fetch all the relevan ...

What's preventing me from accessing children in three.js group?

Having this particular class declaration class GameManager { constructor() { this._activeObjects = new THREE.Group(); } get randomGeometry() { const geometry = new THREE.BoxGeometry(0.1, 0.1, 0.1); return geometry; } get randomMat ...

Making HTTP requests to the Gmail API

Today, I dedicated most of my time to learning how to utilize the Gmail API with node.js. Following Google's QuickStart guide, I successfully got the API up and running fairly quickly. It seemed like there were two methods for making API requests. One ...

Calculate averages of an array and show them when the page loads using Vue

In my coding project, there is an array named products that follows this specific structure: { "_id": "150", "name": "Milk", "description": "Skimmed", "price": "10", "ratings": [ ...

Vue fails to reflect changes in data when it is updated

I have a page where I can access data by calling domain.com/subpage?soundfile=something Using the fetch method, I extract the query parameter from the URL to retrieve the necessary information. The retrieval process is successful as indicated by the data ...

Error in custom class using vanilla JavaScript: "Error: Unable to assign innerHTML to an undefined property"

Apologies for the ambiguous title, but I am struggling to pinpoint the exact issue at hand... I'm essentially guessing my way through this problem. This marks my initial venture into creating a reusable Javascript class. Below is a simplified version ...

What is the reason behind the Nexus 4 (with Chrome for Android) displaying a window size of 384x519 while the screenshot depicts it as 768x1038

Currently, I am utilizing media queries to adjust the display based on different screen sizes. However, I have encountered an issue where the screen size is not being accurately reflected in CSS. For instance, on the Nexus 4 device, the display is renderin ...

Having trouble with accessing PHP data through jQuery's AJAX response

Having just started exploring AJAX, I'm facing an issue with a simple login script using jQuery 1.6.4. The AJAX function sends the email address and password to 'login.php' upon clicking a button. Everything seems to be working smoothly unti ...