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

AngularJS's $resource module returns an empty array as a response

I am trying to display a table with items from JSON data. I have created a Service that returns the JSON data. In my controller, I am querying the Service to receive an array of data. It's a little confusing because I am putting the response in a new ...

unable to effectively test promises with stubs using nodejs mocha

Currently, I am facing a couple of challenges when attempting to perform unit testing on promises using Mocha. 1) The main issue I encounter is an Error: Timeout of 2000ms exceeded. For async tests and hooks, ensure "done()" is called; if returning a Prom ...

Connect various models together, or create synchronized computed properties

At times, the model abstraction may fall short, leading to the necessity of synchronizing two different models. For instance, I have two lists linked by an angular sortable, which requires a model structure like this: left = [{name:"one"}, {name:"two"}]; ...

javascript code not functioning properly

Something simple! In my asp.net-MVC project, I have a button and an external JavaScript file called mydata.js. This file contains a function called checkJS(). function checkJs() { debugger; alert("your output!!!"); } Here is my code: <div id="m ...

What is the best way to access the image source attribute within a directive?

Here's a straightforward image directive example: (function () { 'use strict'; angular .module('myapp') .directive('imageTest', imageTest); function imageTest() { var directive = { ...

Express & React: Be cautious of client checksum and style while server-side rendering

Recently delving into the world of React server side rendering, I'm currently working on a small demo utilizing technologies such as React, Redux, React Router, and Material UI. The main issue I'm encountering is the following warning. I am uncer ...

What issue is being encountered with this JavaScript generated by PHP?

PHP on the host generates JavaScript code that results in an error stating: missing ; before statement The generated JavaScript code looks like this: try{ obj = document.getElementById('subcat'); }catch(e){} try{ obj.innerHTML = ...

Updating ES6 syntax for superset in array: a step-by-step guide

I am currently working with ES6 React code that generates an array of MiniIcons on a webpage. const MiniIcons = ({miniicons}) => ( <div id="application"> {miniicons.map(miniicon => ( <MiniIcon key={miniicon.id} id={miniicon.id} ...

Javascript Error - Issue with Fuse.js: e.split() function is not recognized

Scenario - I am in need of implementing a fuzzy search feature, and therefore utilizing fuse.js for this purpose. I obtained the code snippet from fuzzy.min.js at https://github.com/krisk/Fuse/blob/master/src/fuse.min.js Challenge - Despite using the cod ...

What is the best way to update my lowdb database directly from the frontend in a next.js application?

As a hobby programmer with experience in React and Firebase, I have recently started using Next.js. I'm curious if I can utilize it as a JSON-based database for local applications on my Raspberry Pi. I have successfully set up LowDB to access data fro ...

What is the best method for retrieving an item from localstorage?

Seeking advice on how to retrieve an item from local storage in next.js without causing a page rerender. Here is the code snippet I am currently using: import { ThemeProvider } from "@material-ui/core"; import { FC, useEffect, useState } from "react"; i ...

Ways to transmit data from autocorrect to a higher-level class

Previously, I raised a question about passing state for React via props on Stack Overflow: Laggy TextField Updates in React. I have now revamped my code using ChrisG's approach, where I store states in the parent component FormSection and pass them a ...

Deactivating elements on a website

Is there a way to prevent multiple transactions due to unintended repeated clicks on a button by disabling all webpage elements when the button is clicked? Suggestions include using a div that can be layered on top of the elements when the button is click ...

Having trouble with the HTML5 canvas for loop not rendering the initial object in the array?

Essentially, I'm attempting to iterate through each letter in a text string (specifically the text "marius"). However, there's an issue where the first letter is not being displayed. When the text is "marius", only "arius" is drawn. I've exh ...

The message from Vee-validate indicates that the validator 'required_if' does not exist within the system

I'm currently implementing vee-validate version 3 with Vue 2.7 in my project. Specifically, this is the entry in my package.json file for vee-validate: "vee-validate": "^3.4.5", My issue lies with getting the required_if rule to f ...

Date selection feature in Material UI causing application malfunction when using defaultValue attribute with Typescript

Recently, I discovered the amazing functionality of the Material UI library and decided to try out their date pickers. Everything seemed fine at first, but now I'm facing an issue that has left me puzzled. Below is a snippet of my code (which closely ...

Firefox displays an error when using jQuery.load(), but Chrome functions properly without any issues

I have created a function that opens a page in a dialog box instead of the main window. The code has been cleaned up and here is the revised version: var baseUrl = window.location.origin + '/static/docs/'; function handleLinkClick(event) { ev ...

How can I display a calendar with a complete month view using ng-repeat?

I was trying to replicate a table similar to the one shown in this image: (disregard the styling). I am struggling with how to properly format the data to create a similar table in HTML. $scope.toddlers = [ { "name": "a", "day": 1, "total": 3 }, { ...

Encountering issues with integrating NPM package into Meteor.js

Having installed both the meteor-npm package and the crypto npm package, I encountered some issues while using it in Meteor. npm: updating npm dependencies -- crypto Despite seeing this output in the console, when trying to use the npm package on the ser ...

Refreshing a view in Laravel after a successful insertion using JQuery Ajax

I have been successfully inserting records into a table using jQuery ajax, and receiving a flash message confirming the successful insertion. However, I am now facing an issue where I do not know how to reload the table to reflect the changes after the rec ...