"Creating and appending a new div element to the DOM using JavaScript

Is there a way to dynamically add an element with the same id when clicking a button that is linked to JavaScript without any existing JS in place? I initially considered using document.write and then appending a div, but this approach did not work for me. Additionally, I have heard that this practice is not recommended.

This is what I currently have:

HTML:

<!DOCTYPE html/>
<html>
    <head>
        <title>wat</title>
        <meta charset= "UTF-8">
        <link rel="stylesheet" type="text/css" href="CssHtmlLapai.css">
        <script src="JsLapai.js"></script>
    </head>
    <body>
        <button type="button" onclick="NewDiv()">Click me</button>
        <div id="first"></div>
    </body>
</html>

CSS:

#first{
    width: 100px;
    height: 100px;
    background-color: red;
}

Answer №1

One way to accomplish this is by using the document.createElement(tagName) method.

Check out more information here

function CreateNewDiv() {
   var newElement = document.createElement("div");

   document.getElementById("parentContainerId").appendChild(newElement);
}

Answer №2

If you want to apply the same CSS styles to multiple elements, it's best to use classes instead of duplicate IDs. Using classes ensures consistency and prevents unexpected behavior in JavaScript.

Instead of using 'id', switch to using 'class' in your HTML:

<!DOCTYPE html/>
<html>
    <head>
        <title>My Page</title>
        <meta charset= "UTF-8">
        <link rel="stylesheet" type="text/css" href="styles.css">
        <script src="script.js"></script>
    </head>
    <body>
        <button type="button" onclick="createNewDiv()">Click me</button>
        <div class="myClass"></div>
    </body>
</html>

To define a class in CSS, use the '.' prefix like this:

.myClass{
    width: 100px;
    height: 100px;
    background-color: blue;
}

In JavaScript, create a new div element with the specified class:

<script>
    function createNewDiv()
    {
        var newDiv = document.createElement("div");
        newDiv.className = "myClass";
        newDiv.id = "someUniqueId"; //optional
    }
</script>

Answer №3

Use this Code Snippet:

HTML:

<!DOCTYPE html/>
<html>
    <head>
        <title>wat</title>
        <meta charset= "UTF-8">
        <link rel="stylesheet" type="text/css" href="CssHtmlLapai.css">
        <script src="JsLapai.js"></script>
    </head>
       <body>
            <button type="button" id="click-me">Click me</button>
            <div id="first" class="common-css"></div>
        </body>
</html>

CSS:

.common-css{
    width: 100px;
    height: 100px;
    background-color: red;
}

JavaScript:

document.getElementById('click-me').onclick = function() {
   var newDiv = document.createElement('div');
   var firstDiv = document.getElementById('first');
   newDiv.setAttribute('class', 'common-css');
   firstDiv.appendChild(newDiv);
};

JSFiddle link: http://jsfiddle.net/vinoddalvi/u4H9h/

Answer №4

If you want to replicate an element using jQuery:

$('button').click(function() {
    $('#first').first().clone().appendTo('body');
});

Check out this example on jsFiddle

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

What is the proper way to transfer data to PHP using AJAX?

I'm facing an issue while trying to send FormData to a PHP file. When I press submit, nothing happens. However, when I send data separately, it works fine. <form method="post" class="code_form" enctype="multipart/form-data& ...

Looping through a Vue Bootstrap modal using a v-for directive

I am working on a Vue Bootstrap modal placed within a v-for loop. I need to replace the '1' in both 'v-b-modal.modal-1' and 'modal-1' with the index value, which I can access as {{ index }} while looping through the items. How ...

Scan webpage for checkbox elements using JavaScript

When my page loads, dynamic checkboxes are generated using the following HTML: <input type='checkbox' name='quicklinkscb' id='quicklinkscb_XX'/> The XX in the ID represents the unique identifier of an item from the dat ...

There seems to be a problem with the Chart property getter as it

I'm in the process of creating an object that corresponds to chartJS's line-chart model <line-chart :data="{'2017-05-13': 2, '2017-05-14': 5}"></line-chart> There is an API I utilize which returns a standard arra ...

What is the process for executing JavaScript within an ASP.Net Web Form application's update panel using server-side code?

I am facing a challenge with implementing JavaScript code within an update panel in my ASP.Net web form application using server-side code. Interestingly, the code I have only seems to work when placed outside of the update panel, and not within it, even w ...

Is sending an AJAX request to a Node.js Express application possible?

Currently, I am attempting to authenticate before utilizing ajax to add data into a database $('#button').click(function () { $.post('/db/', { stuff: { "foo" : "bar"} }, callback, "json"); }); Below is my node.js code: ...

Horizontal alignment of navigation bar items using <ul>

I'm trying to center the bar within the navigation bar vertically, but when I use align-items: center for the bar, it only centers the sign-in button, leaving it slightly above the middle position. nav a{ color:white; } nav{ justify-content: sp ...

The hyperlinks are not functioning correctly on my template

I'm using a template with the following preview link: The template includes an image of a laptop on the left side, with clickable points representing links. My goal is to make these points clickable so that they open specific pages like mbank.pl or ...

ajax memory leakage

Encountering a gradual memory leak issue in Internet Explorer and Firefox while utilizing a mix of ASP.NET AJAX and jQuery. The situation mirrors the one portrayed on this post: Preventing AJAX memory leaks, but with jQuery and ASP.NET AJAX instead of prot ...

Are you attempting to retrieve the most up-to-date trading price of a stock with Python?

After attempting to extract the LTP of a stock with the code below, I am not getting any value in return. Can you identify the error in the following code: from selenium import webdriver from bs4 import BeautifulSoup driver=webdriver.Chrome("C:&bsol ...

Pass the responsibility to another component or initiate an ajax request in react

I'm currently using fetch for my ajax call, which is located within a handleSearch function in the App component. How can I separate this ajax call into its own component? Coming from Angular 1, where services/factories are used, I'm not sure how ...

"Enhance your data manipulation with Angular 2's *ngIf: A stylish

I need some assistance. This is what my HTML code looks like: <a href="/admin/companies" mat-button *ngIf="currentUserRole == 'Admin'" > <mat-icon matBadge="A" >business</mat-icon > Compa ...

What happens when you click and trigger mouseleave?

window.onload = function() { $(".compartir").hover(function() { console.log('hover'); var self = this; setTimeout($(self).addClass('ready'), 500); }, function() { var self = this; console.log('leave'); ...

Preventing Copy and Paste and Right-Click Actions With JavaScript

Similar Question: How can I prevent right-click on my webpage? Looking to prevent right-clicking and key combinations like Ctrl+V & Ctrl+C on a webpage using JavaScript. I have a form where customers need to input their details, and I want to avoid ...

Unable to modify a variable within a request

Having trouble updating a variable within a request? It seems like the variable doesn't change when it should. const request = require("request"); var all = JSON.parse(body); var steamplayer = all['response']['players']['play ...

Use jQuery to create a toggle effect with unique attributes and incorporate AJAX functionality

When using this jQuery plugin for creating toggles, I encountered an issue with multiple toggles having the same IDs and classes. This made it difficult to identify a specific toggle to apply auto load ajax when the value changed. I'm wondering how I ...

The function did not receive the parameter when ng-submit was executed

I created a function called reset(username) to log whatever is entered into the input field with ng-model="username". However, I am not seeing anything in the console. Why is that happening? Here is my function: $scope.reset = function (username) { co ...

Printing CSS in ASP.NET without a print dialog box or a pop-up confirmation message after successful printing

My goal is to create a list of greeting cards, each printed to a specific size (A4 folded down the longer edge), using HTML and CSS. I want the cards to be rotated 90° on the page. Ideally, I'd like to print the list without viewing the HTML and bypa ...

"Once the item was returned, its style seemed to have disappeared from

Within an html form, there is a table that can be hidden or displayed based on the selection of a radio button. However, it seems that when the table is hidden and then shown again, one of the style settings is lost. It is desired to maintain the same layo ...

Tips for finding and showcasing content from a JSON file in an HTML format

A list of project names is being displayed in the side bar by retrieving them from a JSON result. When a user clicks on any of the listed project names on the side bar, it will show the details of that specific project. Additionally, there is now a search ...