ArticleZip > How To Display Div After Click The Button In Javascript Duplicate

How To Display Div After Click The Button In Javascript Duplicate

When you're working on a web project, you might come across the need to display a `div` element after clicking a button using JavaScript. This functionality can enhance user interaction and provide a more dynamic experience on your website. In this guide, we'll walk through the steps to achieve this effect by duplicating the `div` element.

Let's start by creating a simple HTML file that contains a button and a `div` element that we want to duplicate. Here's an example markup to get us started:

Html

<title>Display Div After Click</title>


    <button>Click me</button>
    <div id="originalDiv">Original Div Content</div>


    function duplicateDiv() {
        let originalDiv = document.getElementById('originalDiv');
        let clonedDiv = originalDiv.cloneNode(true);
        
        document.body.appendChild(clonedDiv);
    }

In this code snippet, we have a button with an `onclick` event that triggers the `duplicateDiv()` function when clicked. The `duplicateDiv()` function first selects the original `div` element by its ID and then clones it using the `cloneNode()` method with the argument `true` to clone all child elements and their descendants.

Next, the script appends the cloned `div` element to the `body` of the document, which effectively displays a duplicate `div` each time the button is clicked.

To style the duplicated `div` elements and make them visible on the page, you can add CSS rules to your HTML file or an external stylesheet. Here's an example CSS code snippet to give the duplicated `div` elements a distinct look:

Css

div {
    margin-top: 10px;
    padding: 10px;
    border: 1px solid #333;
    background-color: #f0f0f0;
}

By adding this CSS snippet to the `head` section of your HTML file or an external stylesheet, you can customize the appearance of the duplicated `div` elements to match the design of your website.

In conclusion, displaying a `div` element after clicking a button in JavaScript by duplicating it is a straightforward process that can add interactivity to your web projects. By following the steps outlined in this article and customizing the styles to suit your design preferences, you can enhance the user experience and make your website more engaging.

×