Create a duplicate of a div using JavaScript and modify the IDs of the inner elements within

I have two static div tags with a select tag and a text box inside, each with different IDs. When I clone the tag, it duplicates the same div tag in the DOM. How can I change the inner elements' tags?

Below is the code snippet:

        <div id="masterGrade" style="border-style: solid; width: 200px">
        <select id="selectGrade1">
            <option value="grade1">Grade 1</option>
            <option value="grade2">Grade 2</option>
            <option value="grade3">Grade 3</option>
            <option value="grade4">Grade 4</option>
        </select>
        <input type="text" id="text1"/>
    </div>
    <div style="border-style: solid;width: 200px">
        <select id="selectGrade2">
            <option value="grade1">Grade 1</option>
            <option value="grade2">Grade 2</option>
            <option value="grade3">Grade 3</option>
            <option value="grade4">Grade 4</option>
        </select>
        <input type="text" id="text2"/>
    </div>

My JavaScript function:

    $scope.addGrade = function() {  

        var div = document.getElementById('masterGrade'),
        clone = div.cloneNode(true); 
        clone.id = "some_id";
        document.body.appendChild(clone);
    }

If you have any suggestions or solutions, please share them. Thank you!

Answer №1

Mixing the DOM api with angular is not considered a recommended practice. It is preferable to follow the Angular way (ng-repeat)

var app = angular.module('app', []);
app.controller('ctrl', function($scope) {
  $scope.grades = [{}];
  $scope.addGrade = function() {
    $scope.grades.push({});
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app='app' ng-controller='ctrl'>
  <button ng-click='addGrade()'>Add</button>
  <div style="border-style: solid; width: 200px" ng-repeat='grade in grades'>
    <select ng-model='grade.list'>
      <option value="grade1">Grade 1</option>
      <option value="grade2">Grade 2</option>
      <option value="grade3">Grade 3</option>
      <option value="grade4">Grade 4</option>
    </select>
    <input type="text" ng-model='grade.text' />
  </div>
  {{grades}}
</div>

Fiddle Demo

Edit: When dealing with the index, utilize $index. The ngRepeat directive creates a template for each item in a collection. Each template has its own scope, where the loop variable represents the current collection item, and $index refers to the item index.

var app = angular.module('app', []);
app.controller('ctrl', function($scope) {
  $scope.grades = [{}];
  $scope.addGrade = function() {
    $scope.grades.push({});
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.10/angular.min.js"></script>
<div ng-app='app' ng-controller='ctrl'>
  <button ng-click='addGrade()'>Add</button>
  <div style="border-style: solid; width: 200px" ng-repeat='grade in grades'>
    <label for="select{{$index}}">Grade {{$index}}:</label>
    <select id='select{{$index}}' ng-model='grade.list'>
      <option value="grade1">Grade 1</option>
      <option value="grade2">Grade 2</option>
      <option value="grade3">Grade 3</option>
      <option value="grade4">Grade 4</option>
    </select>
    <br>
    <label for="text{{$index}}">Text{{$index}}:</label>
    <input id='text{{$index}}' type="text" ng-model='grade.text' size='10' />
  </div>
  {{grades}}
</div>

Fiddle Demo

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

Fixing TypeError in React App: How to Resolve the "Cannot read property 'prototype' of undefined" Issue

I am completely new to JavaScript and I am struggling to understand the error that keeps popping up. After doing some research, it seems like the error could be due to a poorly written function or something along those lines. Here are the classes involved ...

The failover process for PayPal involves seamless transitions to backup systems in the

I am currently assisting a client with a unique architecture setup: Back End Running on Java Server Front End Powered by Proxy (Node JS + Express application) For security reasons, all requests made to the server must pass through the Proxy. We ar ...

Issues with JQuery scroll() / scrollTop() functionality in Internet Explorer and Firefox

Our current script showcases a dotted line starting from the top of the screen leading to an up arrow. The position of the arrow changes based on how far the user has scrolled down the page, allowing them to click on the arrow and scroll back to the top. W ...

Flexible array for varying results

I'm attempting to display a random selection from two arrays by alternating between them, with no concern for storage capacity. Unfortunately, my code is not functioning correctly and I am unsure why. var male = ["have a shot", "item 2", "item 3"]; ...

Combining ServiceStack with MVC and AngularJs for optimal integration

Setting up web.API with MVC is a breeze - just keep the WebApiConfig.cs as default, create a new web.API controller, and then in your javascript make calls using $http.get("api/..."). I'm interested in achieving the same functionality using service s ...

Execute a function once all images have finished loading

My current approach involves utilizing a function to load images from an array: for (var i = 0; i < images_list.length; i++) { var img = new Image(); img.onload = function() { images_objects.push(this); ...

What are the steps for implementing oncopy in Angular?

If I attempt the following: <div oncopy="myfunc('{{angularvar}}')">Copy me</div> Then an error message is displayed: Interpolations for HTML DOM event attributes are not permitted. It is recommended to use the ng- versions (such ...

Are there more efficient methods than having to include require('mongoose') in each models file?

Is it possible to only require mongoose once in the main app.js file and then pass it to other files without loading it again? Will the script do extra work every time the same module is required? var mongoose = require('mongoose'); I'm wo ...

How can we toggle a function to expand or collapse fields generated in an ngFor loop?

One of my challenges involves managing a div that is repeated using *ngFor in Angular. This results in multiple divs on the page, each containing collapsible fields that can toggle. Essentially, I have nested collapsible fields within other collapsible fie ...

Error in Redux reducer file caused by an incorrect data type in action.payload

I have encountered a type error in my reducers' file where it says that my 'Property 'address' does not exist on type 'number | { connection: boolean; address: string; }'. This issue is arising in my React application while us ...

What is the method for creating an array of strings in VueJS?

In my VueJS and Vuetify project, I am working on creating a modal that allows users to input strings into a text field. What I aim to achieve is adding the inputted string to an array when the user clicks on create button. For example, if I enter 'inp ...

Combine, condense, and distribute JavaScript files using Express without applying gzip compression to the response

Currently, I am developing a web application using Express. My goal is to merge, minify, and serve .js files efficiently. To achieve this, I have created a middleware with the following code: var fs = require('fs'), path = require('path ...

Comparing Fetch and Axios: Which is Better?

Currently delving into the realms of axios and the fetch API, I am experimenting with sending requests using both methods. Here is an example of a POST request using the fetch API: let response = await fetch('https://online.yoco.com/v1/charges/&ap ...

Updating dropdown values using another dropdown through AJAX in Node.js: A step-by-step guide

My dilemma involves two dropdown menus: one for selecting the main category and another for choosing a subcategory. The goal is to dynamically populate the subcategory based on the main category selection. In my attempts so far, I have utilized JQUERY and ...

Troubleshooting ASP.NET MVC3: The mystery behind why my custom validation attributes always seem to fail

After completing several tutorials, I have successfully implemented my models from a library file (dll). Everything seems to be functioning correctly except for one issue. Here is my model: public class RoomBookingInsert { public Int32 CostCentreNo ...

Guide on adding an additional key:value pair to a sub document in a MongoDB collection

I'm facing difficulties trying to add a new key:value pair to an existing object in a MongoDB document. I've experimented with $each, $push, and $addToSet, but it seems like those are intended for arrays. I then attempted $set, but that only upd ...

Retrieving the output of an asynchronous function within another function in JavaScript

I'm facing an issue with the Chrome API functions being asynchronous, making it difficult for me to get their return value. Here's a snippet of code that demonstrates my problem. I'm working with AngularJS. $scope.storageGet = function( ...

Obtain the value of "data-something" attribute from an <option> element within a <select> element

Can anyone help me with this HTML snippet? <select id="something"> <option value="1" data-something="true">Something True</option> <option value="2" data-something-else="false">Something Else False</option> </selec ...

Guide to updating information in Firestore using Node.js, embedded in a map array

Encountered an issue with the following error message: Error: Unable to access 'set' property of undefined. I am attempting to update the endTime field in my script for each user, calculate total hours worked, and then update the 'totalTi ...

A simple way to verify which option has been chosen has been altered

I am examining the code snippet below: <select class="select" id="choice-item" aria-invalid="false"> <option value="#opt0" selected="selected">32 bits</option> <option value="#opt1">64 bits</option> </select> M ...