Duplicating a div and modifying its properties

After conducting extensive research, I was unable to find a solution to my issue. I attempted to create a drop-down select element using CSS to change the background color, but encountered an obstacle while trying to clone it with JavaScript. The new copy did not inherit the attribute changes, resulting in it retaining the original color. Feel free to experiment by adding content and attempting to change the colors.

As a newcomer here, I may struggle to include code, so here are links for you to try:

http://jsfiddle.net/gabry501/FUyA3/ or on GitHub

https://github.com/gabry501/Test-Color/blob/master/test.html

HEAD

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>


<script type="text/javascript">

function cloning() {

    var container = document.getElementById('fine');
    var clone = document.getElementById('contenitore').cloneNode(true);
    container.appendChild (clone);

}

STYLE

select option,
select {
    background-color:white;
    width:200px;
    height:200px;
}

select option[value="1"],
select.o1
{
    background-color:blue;
}

select option[value="2"],
select.o2
{
    background-color:red;
}

select option[value="3"],
select.o3
{
    background-color:orange;
}

BODY

<div style="width:1100px;
height:250px;" id="contenitore">

SCRIPT

<script>$('select[id$=-status][id^=id_item-]').children().each(
    function (){
        if($(this).val() == 0){
            $(this).css('backgroundColor','white');
        }
        if($(this).val() == 1){
            $(this).css('backgroundColor','green');
        }
        if($(this).val() == 2){
            $(this).css('backgroundColor','red');
        }
        if($(this).val() == 3){
            $(this).css('backgroundColor','orange');
        }
    }
);</script>

<script>    
$('select[id$=-status][id^=id_item-]').change(function (){
    var color = $(this).find('option:selected').val();

    $(this).removeClass('o1 o2 o3').addClass('o' + $(this).find('option:selected').val());
}).change();

Answer №1

It appears that you are relying on a listener to adjust the style. Listeners added through the use of addEventListener do not carry over to a cloned element, so you will need to attach them separately.

Keep in mind that listeners added directly in the HTML or through attachEvent will be copied when cloning an element.

Answer №2

cloneNode() function only duplicates the data of the specified element, excluding event listeners. To copy event listeners as well, you must do so manually.

Alternatively, you can utilize the jQuery clone() method.

function cloning() {

        var container = document.getElementById('fine');
        var clone = $(document.getElementById('contenitore')).clone(true);
        $(container).append(clone);

    }

Check out the Fiddle here

PS: Your code seems cluttered. Consider simplifying it for better readability.

UPDATE: I made some modifications to the code.

1.) Removed the click event from HTML and attached it through script.

2.) Replaced the ID's with class names, as IDs in a document should be unique.

3.) Eliminated extra styles and replaced them with a simple class name.

4.) It's advisable to separate style and script into individual files rather than embedding them in HTML.

5.) For proper functionality, ensure the styles and script are placed in the corresponding tags I have indicated.

HTML:

<!doctype html>
    <html>
       <head>
         <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
        <meta charset="UTF-8">
        <title>Untitled Document</title>
        <style type="text/css">
            // Insert Styles here
        </style>
      </head>

       <body>
          <div style="width:1100px; height:250px;" class="contenitore">
             <select  name="item-0-status">
                <option value="" disabled="disabled" class="optionGroup">SELECT 
                      COLOR</option>
                <option value="1"> BLUE</option>
                <option value="2"> RED </option>
                <option value="3"> ORANGE</option>
             </select>
          </div> <!--Contenitore -->

          <div id="fine"></div>

          <br>
          <div id="bottone">
          <input id="btn" type="button" Value="ADD">
         </div>
           <script type="text/javascript">
               // Script Goes Here
           </script>           

       </body>
    </html>

Javascript:

$(function() {
    $('select[name="item-0-status"]').change(function() {
        $(this).removeClass('o1 o2 o3').addClass('o' + $(this).val());
    }).change();

    $('#btn').on('click', function() {
        var container = document.getElementById('fine');
        var clone = $(document.getElementsByClassName('contenitore')[0]).clone(true);
        $(container).append(clone);
    });
});​

Styles:

#bottone {
   float:left;
   text-align:left;
   clear:left;
   margin-top:20px;
}

select option, select {
   background-color:#FFF;
   width:200px;
   height:200px;
}

.o1 {
    background-color:blue;
}

.o2 {
   background-color:red;
}

.o3 {
   background-color:orange;
}​

See the Updated Fiddle here

Answer №3

To handle dynamically added elements, make sure to use $('.el').live('change', fn) instead of $('.el').change(fn).

Check out this demonstration on jsfiddle: http://jsfiddle.net/ABC123/4/

Answer №4

Experience the power of deep cloning by using $(selector).clone(true) - this will ensure that events are also duplicated

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

Customized settings saved in local storage using JavaScript

Here is the script I am currently using for my app: <script> if (localStorage.getItem("0") === null) { //do nothing } else if(localStorage.getItem("1")===null{ } else if(localStorage.getItem("2")===null{ } else if(localStorage.getItem("3")===null ...

If the browser closes and there is no recipient to receive the data requested by my ajax, what ultimately becomes of that data?

On my website, utilizing vb.net / c# programming, there is javascript ajax code that retrieves data from the database and sends JSON back to the page. If, just before the ajax call is able to receive the JSON, the browser is closed or the page is redirect ...

Identify modified fields and transmit using jquery and ajax communication

Unable to find a solution for this problem... I have created a form that uses jQuery to detect changes in field values and adds the 'edited' class if it has been edited, and 'editable' if it has not. When a button is clicked, I would ...

The map() function efficiently retrieves all object values from an array in the backend simultaneously

Using axios, I am downloading backend structure data. The data is structured as advancedProfile.technologies (an array with 5 objects) with keys {title, link, category, date, id}. Afterwards, I am rendering divs using the map function. The code line loo ...

Is it possible to efficiently iterate through map keys in axios using Vue.js?

Currently, I am working on Vue.js exercises that I have created. I am successfully populating a table with data from a JSON API, but I have encountered a challenge. The API contains multiple keys with similar names (strIngredient1, strIngredient2, strIngre ...

What is causing the UI to change every time I add a tag to refresh the web view?

Recently, I added a pull-to-refresh feature to my React Native webview app using the react-native-pull-to-refresh library. After implementing the tag, I noticed that the UI got rearranged with the webview shifted down and the top half occupied by the pull- ...

Issue with VueJS compilation: JSON data import causing failure

I'm attempting to bring in a static .json file within the <script> section of a .Vue file using the code snippet import Test from '@assets/test.json' From what I've gathered about webpack, this should work effortlessly. I have ev ...

Sending requests across domains from HTTPS to HTTP with callback functionality, and reversing the process

Prior to our conversation, I had created it using Flash. I uploaded a special file (crossdomain.xml) on the server side (https), while the Flash component was placed on the http server. Although they belong to different domains on the https and http serv ...

JavaScript toggle display function not functioning properly when clicked

I've been attempting to create a drop-down list using HTML and JavaScript, but for some inexplicable reason, it's just not functioning as expected despite scouring through countless tutorials on YouTube. Below is the snippet of code that I'm ...

Adjusting the color of the legend on a LineChart in ExtJS 4 on-the-fly

I've been trying to find information on how to modify the color of the x legend in a Line chart without success. Can anyone help me with this? I have included an image of the chart for reference. ...

How can I dynamically alter the color of a table row without using _rowVariant?

I am utilizing a bootstrap-vue table to showcase information retrieved from a JSON file. One piece of information I receive is an integer labeled "Status", and I aim to adjust the row's color based on this variable. For instance, if the Status equals ...

What is the best way to position a tooltip near an element for optimal visibility?

One div is located on the page as follows: <div id="tip"> Text for tip goes here... </div> And another one can be found below: <div class="element"> Text for element goes here... </div> There is also a piece of JavaScript ...

Access RSS feeds externally without relying on any third-party libraries or server-side processing

Looking to integrate an RSS parser that can parse feeds using jQuery/JavaScript without relying on the Google Feed API or any server-side solutions. The goal is to have auto-updating RSS feeds without overloading the server with multiple requests from user ...

Dynamic rendering of components in React can be achieved by passing arguments to functions

In my single-page application (SPA), I have multiple sections (Components) that I want to toggle based on a cookie. My idea is to create a function that can switch between two different components by passing their names as arguments. My proposed approach: ...

How to dynamically add a form to your website

Looking to dynamically insert a form on a page based on the value selected from a datalist, all without having to reload the entire page. <form action='#' method='get'> <input list="category" name="category"> <da ...

Angular 2: Changing HTTP Requests

I am trying to include a single parameter in all my web requests to disable caching forcibly. My goal is to append ?v=1535DC9D930 // Current timestamp in hex to the end of each request. I am coding this in plain ES5 JS, but the documentation is in Types ...

Can the characteristics of a group of objects be combined and sorted based on a different attribute?

Feeling a bit puzzled by my title, Here's the issue at hand - I aim to destructure an array of objects to utilize its properties in a chartJS Line Graph. Take a look at the replicated array below: [{ "page": "Page 1", &qu ...

Spin the content of the HTML body using CSS

I need help rotating the HTML body using CSS. Here is the code I have tried so far: -webkit-transform: rotate(90deg); -moz-transform: rotate(90deg); -o-transform: rotate(90deg); -ms-transform: rotate(90deg); transform: rotate(90deg); I have tested this i ...

The feature 'forEach' is not available for the 'void' type

The following code is performing the following tasks: 1. Reading a folder, 2. Merging and auto-cropping images, and 3. Saving the final images into PNG files. const filenames = fs.readdirSync('./in').map(filename => { return path.parse(filen ...

What does ngModel look like without the use of square brackets and parenthesis?

Can you explain the usage of ngModel without brackets and parentheses in Angular? <input name="name" ngModel> I am familiar with [ngModel] for one-way binding and [(ngModel)] for two-way binding, but I am unsure what it means when ngModel ...