Create a copy of an element without altering the original

Currently, I am attempting to create a duplicate of a class and ensure that it remains unaffected when the original is altered. So far, I have tried:

$(".newclass").addClass("oldclass");

However, this method does not copy the content.

var _elementClone = $(".oldclass").html();
$(".newclass").html(_elementClone);

This approach successfully transfers all the contents of the div.

My problem arises when any changes are made to the parent class 'oldclass,' such as:

$('.oldclass').hide();

<style> 
.oldclass{visibility:collapse}
</style>

In these instances, the new class also undergoes modifications. How can I create a new class that remains unchanged when alterations are made to its parent?

Answer №1

To make a copy of an element, you can extract its outer HTML, utilize jQuery to modify its ID, class, or other attributes, and then insert it into the Document Object Model (DOM) as independent elements.

FOR INSTANCE

HTML:

<div id="first" class="top">First Div</div>
<div id="second" class="middle">Second Div</div>
<div id="third" class="middle">Third Div</div>
<div id="last" class="bottom">Last Div</div>

Javascript:

var divs=$(".middle");

$.each(divs,function(i,el) {
    var newdiv = $(el.outerHTML);
    newdiv.attr("id",newdiv.attr("id")+"-copy");
    newdiv.removeClass("middle").addClass("middle-copy");
    divs.eq(i).after(newdiv); 
});
$("#second-copy").html("copy of second div");
$("#third").html("original third div");
setInterval('$(".middle-copy").toggle()',1000);

Fiddle: http://jsfiddle.net/1a2b3c4d5e6/

Answer №2

When you assign the .newclass to .oldclass in the first line, it means that when you later hide the .oldclass, all elements with the class .newclass will also be hidden. This is because any element with the class .newclass is automatically also a part of the .oldclass.

Instead of trying to hide the individual elements, consider using the function .append() to add a child element to a parent element.

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

Adding attributes to parent DOM elements of a component in Angular2: A Step-by-Step Guide

I'm working with the following code: ... <div class="container"> <div class="fancy"> <fancybutton></fancybutton> </div> <button (click)="addAttribute()">Remove</button> <button (click)="remAttr ...

Discovering intersection points along a line between the previous and current positions of the mouse in Three.js

I am working on a project in Three.js where I have a scene filled with lines. Everything is working smoothly when the mouse moves slowly, as I am using the raycaster method to check for intersections with the lines. However, the issue arises when the mouse ...

Why does i18next only function on http://localhost:3000/de (landing page) in NextJS and not on http://localhost:3000/de/about?

I'm new to this and feeling lost on how to tackle this issue. I tried following the instructions on https://github.com/i18next/next-i18next, but I'm struggling with index.js. When I toggle /de on my landing page, it translates correctly in the UR ...

Clicking on numerous hyperlinks using Selenium IDE

Looking to automate some websites using Selenium IDE? Here's how you can achieve this: Click Click Link 1 do some clicking inside that link go back to the list of links Click Link 2 do some clicking inside that link go back to the list of links Cli ...

Ways to add a substantial quantity of HTML to the DOM without relying on AJAX or excessive strings

Currently, I am looking to update a div with a large amount of HTML content when a button on my webpage is clicked. The approach I am currently using involves the .html() method in JQuery, passing in this extensive string: '<div class="container-f ...

Getting rid of the upper boundaries and outlines of the Bootstrap table

React code: <div style={{paddingLeft: '8px', paddingRight: '8px'}}> <div className="-subtitle"> <div className="pull-right" style={{marginBottom:'5px' ...

Invisible anchor rows in GWT's UIBinder grid view

While developing my GWT application, I encountered an issue in a composite class where I am creating a Grid UI binder. Each cell of the grid contains an anchor UI Binder element. However, upon loading the page in the application, I noticed that the table w ...

Send back a JsonResult containing a collection of objects from an MVC controller

In my MVC controller, I have a straightforward method: [HttpPost] public JsonResult GetAreasForCompany(int companyId) { var areas = context.Areas.Where(x => x.Company.CompanyId == companyId).ToList(); return Json(areas); } Here is the structure ...

Toggling designs with a simple click

I'm currently working on a ReactJS project and I'm trying to figure out how to change the color of a button when it's clicked. I've heard about the Ripple API, but I find it quite complex to use. Can anyone offer some advice on how I ca ...

What is the best way to show an image on the screen once a submit button is clicked?

I have a hidden loader-bar gif that I want to display when the user submits a form. Here is the code: <p class="loadingImg" style="display:none;"><img src="/design/styles/_shared/classic-loader.gif" alt="" /></p> Is there a way to ...

Is it possible to modify the class attribute of an HTML element in PHP upon clicking an input?

In this assignment, I am restricted to using only PHP and cannot incorporate JavaScript. Currently, my code is set up to detect a post from an input type="submit" and then check for empty or filled text inputs. The code currently echoes text based on the c ...

Loop through the JSON data and display any empty strings

I encountered an issue while trying to convert an object string from a list of arrays using the JSON.parse method. Despite successfully converting the object string to an object, it appears empty when used within ng-repeat. Jade .item.col-md-4(ng-repeat= ...

Ways to ascertain if a view has completed rendering in JavaScript

I am currently building my application using the awesome backbone.js framework. Within my code, I have this layoutView that handles rendering the overall layout and also includes a smaller profile section. The dilemma I'm facing is with the timing o ...

Troubleshooting a problem with a personalized webkit scrollbar in Chrome

Using the CSS property scroll-snap-type: y mandatory; to customize my scrollbar with the following styles: ::-webkit-scrollbar { width: 12px; background: transparent; } ::-webkit-scrollbar-track { background-color: rgba(0, 0, 0, 0.5); -webkit-box-s ...

What is the best way to add selected values from a multi-select dropdown into an array?

Attempting to populate an array from a multiple select dropdown, I've encountered an issue. Despite using splice to set the order of values being pushed into the array, they end up in a different order based on the selection in the dropdown. For insta ...

Stop clicks from interfering with dragging in three.js

My GLTF model in Three.js has objects within it, and I want the camera to zoom in on an object when the user clicks on it. However, I am facing an issue where if the user drags after clicking on an object, a click is triggered upon releasing the mouse butt ...

Limiting the DatePicker in React JS to only display the current year: Tips and Tricks!

I'm currently implementing the KeyboardDatePicker component in my React application to allow users to choose a travel date. However, I am looking to restrict the date selection to only the current year. This means that users should not be able to pick ...

Implementing a New Port Number on a ReactJs Local Server Every Time

As a newcomer to ReactJS, I recently encountered an issue while working on a project that puzzled me. Every time I shut down my local server and try to relaunch the app in the browser using npm start, it fails to restart on the same port. Instead, I have ...

Resize Pictures in Carousel for Smartphones

Currently, I am in the process of optimizing my website for mobile devices. The NivoSlider, which is used throughout the site, does not seem to scale well on smaller screens. Despite trying various methods in the mobile section of my stylesheet such as " ...

Steps to seamlessly integrate puppeteer with an active Chrome instance or tab

Is there a way to connect puppeteer to an already open Chrome browser and control a specific tab? I believe it may involve starting Chrome with the --no-sandbox flag, but I am unsure of the next steps. Any assistance on this matter would be greatly apprec ...