Javascript: The first div that is duplicated is continuously reproduced

I have created a script that copies the entire div into another div successfully.

Check out the code below:

Script:

var x = 1;
    function duplicate() 
    {
        var firstContent = document.getElementById('1');
        var secondContent = document.getElementById('2');
            if(x <=10)
            {
                x++;
                var targetDiv = document.getElementById('m')
                var newDiv = document.createElement("div"); 
                newDiv.innerHTML = (secondContent.innerHTML = x + firstContent.innerHTML);
                targetDiv.appendChild(newDiv);
            }
    }

HTML:

<input type="button" onclick="duplicate();" value="+" />

<div id="m">

<div id="1">
test
</div>
<div id="2"></div>
</div>

Although the code works, it keeps duplicating the content above like this:

OUTPUT:

1st OUTPUT:

test
2 test
2 test

2nd OUTPUT:

test
3 test
2 test
3 test

EXPECTED OUTPUT:

1st OUTPUT:

test
2 test

2nd OUTPUT:

test
2 test
3 test

Answer №1

Take a look at the revised javascript code below. Make sure to update your current code by using + instead of =.

var b = 2;
function sum() {

    var xContent = document.getElementById('3');
    var yContent = document.getElementById('4');
    if (b <= 20) {
        b++;
        var target = document.getElementById('n');
        var newDiv = document.createElement("div");
        newDiv.innerHTML = (yContent.innerHTML + b + xContent.innerHTML);
        target.appendChild(newDiv);
    }
}

Check out the live demo Here

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

Adjust the position of the background when hovering with the mouse to create a right

Currently, I am implementing a background perspective change with the use of mousemove. However, an issue arises with the right margin of the image after moving it. Everything looks fine initially. Any suggestions on how to prevent this problem? https:/ ...

What could be the reason for the malfunction of my flexbox layout?

I need to create a layout with three divs in a row. The first div should have a fixed width, the second div should expand until it reaches a "max-width", and the third div should take up the remaining space. Everything works fine until the text inside the ...

Converting PHP arrays into JavaScript arrays with the help of json_encode()

Is there a way to pass an array from PHP to the JavaScript function console.log()? I'm currently simulating a database and need help with this specific task. Despite not having an array declared in my code, I attempted to use the .getJSON() function w ...

Newbie html question: Why won't horizontal scroll bars appear? The content in the td tag keeps moving to the next line

Is there a way to make text and dropdown list controls appear in one single line within a table cell? I've tried adjusting alignment, width, and various other settings, but the text keeps moving to the next line instead of displaying horizontally. Wha ...

Determine the overall count of instances within an array of arrays at a specific combined distance

In the process of developing a method for conducting proximity search in a positional inverted index, I came across this query on Implementing proximity search in positional inverted index nodejs. This issue pertains to a smaller aspect of the overall prob ...

Having trouble interpreting JSON with Jquery

I am attempting to implement autosuggestion using Solr in conjunction with jQuery. Below is the code I have written for this purpose: $(function() { $( "#artist" ).autocomplete({ source: function( request, response ) { $.ajax({ ...

How to resolve a Cross-Origin Resource Sharing (CORS) error when trying to access a local JSON file

Currently, I am attempting to use vanilla JS AJAX request in order to retrieve a JSON string from a locally stored JSON file. My main objective is to accomplish this without relying on JQuery. The code snippet below was inspired by this answer. Despite my ...

Restrictions on the number of characters based on the size of fonts in an html list sc

Recently, I attempted to implement a ticker message on my website using li scroller. However, it appears that there is a limitation on the number of characters that can be displayed in the ticker message when different font sizes are used. With a smaller ...

What is the best way to extract the first heading tags from a post and showcase the outcome?

Can someone help me with changing the_title() function to a heading tag that I manually input in posts? I have created a post loop list using table code but I am stuck at this point... Desired Title Format: <h3 style="text-align: center;">Title Here ...

The modal form vanishes without any action when the form is clicked outside

Everything was working fine with the form submission until I turned it into a modal using Bootstrap. Now, when the form is rendered in the modal, users can tab and type without any issues. However, if they click on any element within the modal (including t ...

Resetting the selected value in an Angular2 select element after the user makes a change

I have a dropdown menu which the user can select an option from. Initially it has a default value and when the user makes a new selection, I need to ask for confirmation by showing a message "are you sure?". If the answer is NO, then I should revert back t ...

Creating a Bootstrap 4 navigation bar that sticks to the bottom of the page, allowing the main content to smoothly scroll

Despite my best efforts, I can't seem to get this to work as intended. I'm struggling to prevent the "main" content (in this case, the images) from disappearing under the bottom navigation bar. In the provided jsfiddle link, you can see that th ...

i18next backend failing to load files

Hey there! Currently, I am implementing i18next within my Node JS Application. Below is the configuration code for i18next: const i18nextBackend = require('i18next-node-fs-backend'); i18n .use(i18nextBackend) .init({ fallbackLng: &apos ...

Selenium WebDriver Error: Element not found - Element could not be located

Having an issue with clicking on a button that has CSS styling. The code for the button is as follows: <div id="rightBtn"> <input type="submit" class="mainButton" id="dodajTrenera" value="Dodaj" name="dodaj_trenera"> </div> To perform t ...

Burger icon appearing on a computer screen

My navigation bar, created using bootstrap 4 and BEM methodology, is displaying the hamburger menu on desktop devices instead of being hidden. Can someone help me identify what's causing this issue? If you want to take a look at the code, here is the ...

Utilizing Angular to efficiently download and showcase PDF files

Presently utilizing https://github.com/stranger82/angular-utf8-base64 as well as https://github.com/eligrey/FileSaver.js/ for the purpose of decoding a base64 encoded PDF file that I am fetching from a rest API. It successfully decodes and downloads, ...

Having trouble getting past the "Starting metro bundler" step when using the 'expo start' or 'npm start' command?

Currently, I am using React Native Expo to develop a mobile application. The process I followed includes the following steps: expo init myapp cd myapp expo start Initially, everything was running smoothly after executing these three commands. However, as ...

Create a menu using React.js that highlights the active link

In this React.js code snippet, a navbar is rendered with two links: 'about' and 'project'. The 'about' link is initially active and colored red upon page load. When the user clicks on the 'project' link, the navbar s ...

Having difficulty communicating with the smart contract using JavaScript in order to retrieve the user's address and the balance of the smart contract

Hi there, I am a newcomer to the world of blockchain technology. Recently, I created a smart contract designed to display both the contract balance and user data, including the address and balance of the user. The smart contract allows users to deposit fun ...

retrieving data in tabular form from a website

Looking to extract a table from this website by clicking on the "National Data" option. While I could easily download it, my interest lies in learning web scraping techniques. Previously, I utilized Python's Selenium package to automate the process of ...