Create a clone of a div element when clicked using jQuery

In simple terms, I would like to be able to click on the div tagged with the class click-to-add. Upon clicking, another div tagged with the class duplicate should be added above the click-to-add div and directly after the initial duplicate div.

<div class="site-table-row header">
   <div class="site-table-row duplicate">
      <div></div>
      <div></div>
      <div></div>
   </div>
   <div class="site-table-row">
      <div class="click-to-add">Click Me</div>
   </div>
</div>

Your assistance or guidance in achieving this is greatly appreciated. Thank you!

Answer №1

$(document).ready(function (){
  $('button').click(function (){
        $('.header').append($('.header').html())
    
      /* console.log($('.header').html()); */
    })
  
  })
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="site-table-row header">
   <div class="site-table-row duplicate">
      <div>1</div>
      <div>1</div>
   </div>
   <div class="site-table-row">
      <button class="click-to-add">Click Me</button>
   </div>
</div>

Answer №2

Resolved using

$('.click-to-add').on('click', function () {
   $('.duplicate').clone().insertAfter('.duplicate').last();
});

Answer №3

I created this using pure JavaScript, and while it may be of assistance to you in understanding the concept:

  <div class="site-table-row header">
   <div id="duplicatediv" class="site-table-row duplicate">
      <div></div>
      <div></div>
      <div></div>
   </div>
   <div class="site-table-row">
      <div class="click-to-add" onClick="addStuff();">Click Me</div>
   </div>
</div>

<script>
 const addStuff = () => {
   let div = document.getElementById('duplicatediv');
   var x = document.createElement("DIV");                      
var t = document.createTextNode("This is the duplicate.");    
x.appendChild(t);                                           
div.appendChild(x);   
 }

</script>

Link to JSFiddle Example

This code snippet targets a specific div with an ID using getElementById and then adds a new div element to it.

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

Update the content of a bootstrap modal dialog following a successful upload

As part of a new service, I am modifying data in a database using a bootstrap modal dialog. However, I'm facing an issue where the name of a recently uploaded file is not appearing in the modal dialog body until I close and reopen it. Is there a way t ...

Unable to execute response

I'm facing an issue with a form in which I am utilizing jquery.ajax to execute PHP code in the background. Unfortunately, my JavaScript code isn't handling the response from the script properly. Interestingly, if I use if (status == "success"), ...

Improve the performance of your three.js project by utilizing JavaScript arrays instead of importing OBJ or GLTF files

I've noticed that loading OBJ/GLTF/GLB models into my three.js application can be time-consuming. On the other hand, declaring JavaScript arrays of vertices and indices with the same data and creating a new object is much quicker (and reduces file siz ...

Does CSS positioning change depending on the screen size?

I need help fixing the positioning of my logo on the screen. I want it to be 40px from the top and centered horizontally regardless of the screen size. Here is the code that I have: <html> <head> <style type="text/css> body{ back ...

Is there a way I can adjust the dimensions of this gallery?

Here is an example of what I am trying to achieve: http://codepen.io/moransh4/pen/aZOeNO How do I adjust the size of the images to be: width: 370px; height: 200px; Additionally, I want to display only 3 images per view? Ultimately, I would like the lay ...

How can we maintain the existing values of fields when using findOneAndUpdate() without replacing them with null if no new value is provided?

When updating values, the user can choose to update specific fields. However, if only { name: "new name" } is passed in, the email and password fields are also updated but set to "null". Is there a way to update only the fields provided in req.body and le ...

How to resolve useState problem in useEffect when state is not null

Encountering issues with maintaining state in TypeScript React. A Child component passes a 'terminal' object to the Parent via a function called returnTerminal(). This 'terminal' object is then stored as a useState variable named _obje ...

Leveraging geoPosition.js in conjunction with colobox

How can I create a colorbox link that prompts the user for permission to access their location, and if granted, displays a map with directions from their current location? I've managed to get it partially working, but there's an issue when the us ...

The 'id' property cannot be accessed because the data has not been retrieved successfully

After loading my App, the data from Firebase is fetched in componentDidMount. I am currently passing postComments={comments} as a prop. However, before this happens, my app crashes with Cannot read property 'id' of undefined on line const c ...

Empowering user accessibility through intricate custom elements

In the world of web accessibility guidelines, labels are typically associated with form controls like <input> or <textarea>. But what happens when dealing with complex Angular / React / ... components that function as form controls? Picture a ...

The indicated processing instruction is incompatible with the provided payment source. PayPal's hosted fields for credit card payments do not support this specific processor

I'm currently working on integrating credit card payments with hosted fields into my checkout process. However, I keep encountering an UNPROCESSABLE_ENTITY error when making the confirm-payment-source request through the PayPal JS SDK. Here is the co ...

"Encountering an error message stating "Cannot access SpreadsheetApp.getUi() within this context" when attempting to execute the

I've encountered an issue while trying to access the UI object in Apps Script. The code I'm using is something I've used before without any problems, but now I'm getting an error message that says "Cannot Call the .getUI()" method from ...

Guide to sending client-to-client notifications in Angular/Ionic with Firebase Cloud Messaging

I am looking to implement client-client push notifications (not server-to-client). My goal is to send a notification when one user messages another. Is this feasible? How can I achieve this using the structure in the Firebase real-time database? Here is a ...

Set a variable in Node.js to capture the return value of res.json

Embarking on the creation of a social network using Node.js, I must admit that I am quite new to this field. This marks my inaugural post on the subject and I sincerely hope for your understanding. Within my social network project, I aim to implement an a ...

Do websockets provide an effective solution for search box functionality?

Imagine having a textbox or searchbox on a webpage. <input type="search"> Now, what if we want this textbox to interact with the server only when the cursor is actively focused inside it? This application is designed for widespread online usage an ...

What is the process for uploading contentBytes in chunks to a Graph URL generated by the createUploadSession Graph API?

According to Microsoft Graph API documentation, the createUploadSession graph API only provides the URL where attachments can be uploaded. Does anyone know how to upload an attachment chunk by chunk in JavaScript? Thanks in advance. I found this referenc ...

Different ways to display the information of checked checkboxes outside of a div

I am currently working on creating a cinema seating plan with PHP. My goal is to use jQuery to show users the seat they have selected and the price they must pay in the ticketinfo div when a seat is selected, and remove this information when the seat is ...

I'm wondering why my socket.io emit isn't triggering a content update

While working on adapting the IBM angularjs tutorial here into a Yeoman angular-fullstack tutorial, I encountered a slight issue. In my version, when I vote on a Poll, the data does not refresh to display the results. I have tried extensively debugging it ...

Navigating through the portfolio items in Wordpress using a loop for the Next/

I'm new to php and could use some assistance. My clients are requesting a loop for the next and previous buttons on a single page portfolio. Here is the code I currently have: <?php $prev_post = get_previous_post(); $next_post = get_next_post(); ...

Issue with Axios Interceptor not correctly applying token from local storage on initial request

Having an issue with my Vue application where the axios intercept is not applying the authorization token as expected. axios.interceptors.request.use(config => { let token = localStorage.getItem("jwt_token") console.log("Token is: ", token) con ...