I'm trying to add a duplicate element with a different class name as javascript won't add a duplicate object.
I added a button with an event listener on to grab the parent element html and change the class of it but it changes the class of old element as well. Goal is to get a duplicated element in form if someone got multiple phone no. with button you should get an another input option
Here's my code for, doesn't work as i told
add_button.addEventListener('click', e=>{
const data = e.target.parentElement.parentElement
// Grabs the parent element on height 2
console.log(data) // Got the expected data
// ran_value = Math.floor((Math.random() * 100000) + 1); // Tried this function to generate a random value for class
var data_new = data // Created another instance of data
data_new.setAttribute('class', '1') //add class name
console.log(data_new) // changes the class name
// paramsDiv.appendChild(data)
});
Here's my result which I am getting
While in expected result, it should have changed the class name or added it in 2nd div only so duplicate div element can be appended into form paramsDiv.
I don't know exactly your code but you could try to use nodeClone(), see the documentation: https://developer.mozilla.org/fr/docs/Web/API/Node/cloneNode because the problem you have here is probably the "referencing".
Tell me how it goes.
The reason it happens is because when you assign data to new_data, you are not creating a new object. You are simply telling new_data to point at data. For that reason, when you change new_data, data changes aswell. In order to create a completely new element, try this:
var data_new = data.cloneNode(true);
Donot assign with var data_new = data instead clone the node with var data_new = data.cloneNode(true) Reference
Assigning the dom object to a new variable will not create a new independent copy. Instead both variables will point to same location.
If you want to insert the element as the first child, you can make use of Node.insertBefore()
Reference
const add_button = document.getElementById('add-button');
add_button.addEventListener('click', e => {
const data = e.target.parentElement.parentElement
// Grabs the parent element on height 2
console.log(data) // Got the expected data
// ran_value = Math.floor((Math.random() * 100000) + 1); // Tried this function to generate a random value for class
var data_new = data.cloneNode(true); // Created another clone instance of data
data_new.setAttribute('class', '1') //add class name
console.log(data_new) // changes the class name
// paramsDiv.appendChild(data)
});
<div>
Content
<button id="add-button">Add</button>
</div>