Manipulate the content within a div tag by altering its innerHTML property

Is there a simple way to copy content from one div to another while also changing the button's id by incrementing them?

For example:

<script type="text/javascript">
  function add(){
    document.getElementById('two').innerHTML = document.getElementById('one').innerHTML;
  }
</script>

<div id="one">
  <button id="button_1" >Button_1</button>
</div>

<div id="two"></div>

<button onclick="add();">Add</button>

The current implementation does not work as expected.

The desired result is as follows:

<div id="two">
  <button id="button_2" >Button_2</button>
</div>

Is there any straightforward solution for this? Any suggestions are appreciated.

Answer №1

If you're looking to duplicate a button on click, this code snippet might just do the trick for you.

document.getElementById('button').onclick = duplicate;


var i = 0;
var original = document.getElementById('one');

function duplicate() {
    var clone = original.cloneNode(true); // perform a "deep" clone
    clone.id = "one" + ++i; // ensure there's only one element with this ID
    original.parentNode.appendChild(clone);
  
}
<div id="one">
    <button id="button_1" >Button_1</button>
</div>


<button id="button" style="color:red">Add</button>

Answer №2

I decided to make a minor adjustment to the 'id' of the enclosing div.

     <div id="1" class="button">
        <button id="button_1" >Button_1</button>
    </div>

   <button onclick="add();">Add</button>

    <script type="text/javascript">
        function add(){
            var count = document.querySelectorAll('.button').length;
            var newCount = count+1;
            var elDiv = document.createElement('div');
            elDiv.setAttribute("id", newCount);
            elDiv.setAttribute("class", "button");
            elDiv.innerHTML = '<button id="button_"+newCount+">Button_'+newCount+"</button>';

            document.getElementById(count).appendChild(elDiv);
        }
    </script>

However, simplifying the process can be achieved using jQuery. Hopefully, this information proves useful.

Answer №3

Have you been searching for a solution like this? With a solid understanding of jQuery traversal, assigning individual IDs to each button may not even be necessary. A shared class could potentially meet your needs perfectly.

$(function() {
    var last = $('.container');
    var curr = last;
    
    $('#add').on('click', function() {
        last = curr.clone();
        last.find('button').attr('id', function() {
            return 'button_' + ( $('div.container').length + 1 );
        })
        .html(function() {
            return 'Button_' + ( $('div.container').length + 1 );
        }).end()
        .insertAfter( curr );
        curr = last;
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
    <button id="button_1" >Button_1</button>
</div>
<button id="add">Add</button>

Answer №4

When using jQuery:

function addNewButton( originId, destinationId ){
    item = $('#'+originId).clone();
    btn = item.find('button');
    if( btn.length == 1 ){
        btnId = btn.attr('id');
        num = btnId.match(/\d+/g);
        num = parseInt(num[0]) + 1;
        btn.attr('id','btn_' + num);
        btn.html('Button_' + num);
    }
    $('#'+destinationId).html(item.html());
}

To create a new button simply call:

addNewButton('originalBtn','newLocation');

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

Spinning a div using Jquery

I'm having trouble getting a div to rotate. Despite checking the console, I haven't encountered any warnings or errors. If you'd like to see the JSFiddle version of it, feel free to take a look. Below is the code snippet I've been usi ...

Tips for locating numerous div IDs within JavaScript snippets

In my Bootstrap 4 project, I came across a helpful solution on Stack Overflow for creating a dropdown accordion style using JavaScript (Twitter Bootstrap: How to create a dropdown button with an accordion inside it?). I customized the script for my website ...

How to center a responsive image in a container using Bootstrap

How can I properly center my banner and place the logo above it? Currently, both elements are not centered as desired. View the live version here: http://codepen.io/anon/pen/waYBxB HTML Code: </head> <body> <!-- LOG ...

Choose all HTML checkboxes that have the onClick attribute linked to href

I need help with setting the onClick function on a href element that can select all checkboxes. My current code successfully selects all checkboxes, but I would like to be able to deselect them when clicking the button again. Any suggestions? HTML <in ...

Encountering the error message "Function.prototype.bind.apply(...) cannot be invoked as a constructor

I'm attempting to implement Controller Inheritance in AngularJS (1.6.9), but encountering an error in the console: Function.prototype.bind.apply(...) is not a constructor. Here's the snippet from the HTML file: <!-- Controller Inheritance --& ...

Include jQuery, jQuery UI, and plugins seamlessly to avoid any version conflicts

My goal is to inject my custom code into a webpage using a bookmarklet. This code requires jQuery, jQuery UI, and additional plugins to be included on the page. I'm aware of the noConflict function, but I have concerns about potential conflicts if ot ...

Does the functionality of Protractor rely on a specific version of AngularJS?

Recently, I began exploring the world of Protractor. One burning question on my mind is its limitations and whether it relies heavily on a specific version of AngularJS. ...

Issues extracting parameters from URLs with React-router version 5.2

I am working on a component called ViewRestaurant.js, which is part of a react-router setup (using version 5.2). The goal is to access a dynamic URL parameter ("/view-restaurant/:id", specifically the id). In my App.js file (the main data loader ...

Enabling withCredentials in Angular 6 for every HttpClient request is crucial for maintaining consistent authentication and

Is there a method to set { withCredentials: true } as the default for every httpclient call, instead of having to add it manually each time? import { HttpClient } from '@angular/common/http'; ... constructor(private httpclient: HttpClient) { } ...

Extracting a floating picture from an Excel spreadsheet using ReactJS

Is it possible to extract an image from an Excel sheet that is not contained within a cell, but instead appears to be floating above the cells? The XLSX library only gathers cell information and does not provide a solution. Are there alternative methods su ...

What is the correct way to define a function parameter when using AngularJS Emit?

I've been exploring the emit feature in AngularJS and had a question about passing a function as an argument. In the Parent Controller: $scope.$on("getChildFunction", function(event, func) { console.log("The function is...", func); }) In the Ch ...

What's the best way to add contrasting textures to both sides of an airplane?

Issue: I am attempting to create a simple poker card (just for fun) with two different images for the back and front. I have successfully created a Plane geometry with a single texture for both sides, but I am struggling to assign a texture for each side s ...

How can I add animation to an HTML5 video using jQuery?

How can we add animation to an HTML5 video element? <div id="cont"> <video id="movie" width="320" height="240" preload controls> <source src="pr6.ogv" type='video/ogg; codecs="theora, vorbis"'> <source src="p ...

Best practices for showing the SVG element stored in a variable

Encountering an issue with displaying an SVG element stored within a JavaScript variable. The unique situation demands that the SVG is retrieved from the backend as a string value. Upon receiving the response, the SVG data is stored like so: let svgValue ...

Tweet button script fails to work properly when inserted via ajax loading

The following code snippet is used for Twitter integration: <script>!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0];if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src="https://platform.twitter.com/widgets.js";fjs.parentNode.in ...

flexible reaction mechanism for Uploadify

Welcome I am working on a project that involves utilizing two forms within tabs in Ext-JS. Additionally, I am implementing the jQuery framework for my main JavaScript programming tasks. Lastly, I have a global JavaScript object instance (singleton) named ...

When utilizing JqGrid, make sure to utilize the 'aftersavefunc' and 'successfunc' methods prior to executing the 'saveRow' function

After saving a row in order to retrieve the Id for logging, I am encountering an issue where 'aftersavefunc' and 'successfunc' are triggering 'reloadGrid('#telephoneGrid')' before the save operation. It seems that th ...

Master the art of returning two functions within a single function in Javascript with NodeJS and ExpressJS

Currently, I am facing an issue where I need to combine two objects and return them in one function. The challenge lies in the fact that both objects have almost identical properties, but different values. To tackle this problem, I created two separate fu ...

Trouble with jQuery UI Draggable when contained within a div with overflow-y set to auto

I am currently working on creating a user interface that utilizes jQuery UI drag and drop feature. Within this interface, I have a series of flexbox containers. One specific container contains a list where items can be dragged and dropped on top of each o ...

The countdown value in Javascript is not being reset when clearInterval is called

Currently, I am working on implementing a swiper slider with a countdown feature that resets its value every time a slide change occurs. The countdown should restart when the next slide is displayed automatically. However, I have encountered an issue where ...