What is the reason behind cloneNode not including custom properties?

This is in reference to the query about javascript cloneNode and properties.

I have observed the same issue. When using Node.cloneNode, it does not copy any properties that I manually add (as shown in the original post):

    var theSource = document.getElementById("someDiv")
    theSource.dictator = "stalin";

    var theClone = theSource.cloneNode(true);
    alert(theClone.dictator); 

The cloned node, theClone, does not retain the "dictator" property.

I have been unable to find a rationale for this behavior. The MDN documentation mentions that cloneNode should "copy all of its attributes and their values", as specified in the DOM specification.

This inconsistency poses a challenge when attempting to create a deep copy of a DOM tree with custom properties included.

Could there be a solution or explanation that I am overlooking?

Answer №1

In the world of HTML, a property and an attribute are not synonymous.

For setting and getting attributes, it is recommended to use setAttribute() and getAttribute().

let element = document.getElementById("someElement")
element.setAttribute('season', 'summer');

let cloneElement = element.cloneNode(true);
alert(cloneElement.getAttribute('season')); 

Answer №2

Not all elements have corresponding attributes assigned to them. Introducing a custom property to an element does not automatically create an attribute, meaning the behavior in such cases is not defined by the DOM specification.

In reality, the outcome of adding a property to a host object (like a DOM node) is unspecified and there is no guarantee that it will function correctly. It is highly advised to refrain from this practice. Instead, it is recommended to utilize wrappers if you wish to enhance the functionality of host objects (a method commonly used in libraries like jQuery).

Answer №3

Experimented with this code snippet. The cloneNode function does preserve the custom attribute in the clone, but accessing it directly poses a challenge. Here is a potential solution:

 var theSource = document.getElementById("someDiv")
 theSource.dictator = "stalin";
 //or for better cross-browser compatibility
 theSource.setAttribute('dictator','stalin');

 var theClone = theSource.cloneNode(true);
 alert(theClone.getAttribute('dictator')); //use getAttribute to retrieve stored value 

It seems there might be some browser inconsistencies when it comes to cloning expando properties. An interesting testcase from an old Mozilla bug report showcased this issue, wherein Chrome and Firefox failed to replicate the behavior.

//snippet from the bugzilla testcase
var a = document.createElement("div");      
a.order = 50;      
alert(a.order);      
b = a.cloneNode(true);      
alert(b.order);    

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

Steps for displaying mat-spinner for every row in mat-table in Angular 6

I've implemented a mat-table to display a list of executing Jobs. Alongside each row, there are two buttons (Stop and Re-Run) that users can interact with. What I'm trying to achieve is to have a mat-spinner only show up when a Job is running or ...

How can we ensure that the second function is executed only after the AJAX click method has finished in Javascript?

var err=0; $("#addsell").click(function(e) { e.preventDefault(); var data = { title: $('#title').val(), author: $("#author").val(), genre: $('#genre').val(), price: $('#price').val(), ad ...

Style of active link fades after reloading the page

In my MVC application, I am facing an issue with the left menu. I want the active link's CSS to remain styled even after a page reload. Within my CSS file, I have defined the following styles: .navleft li a:hover { background: url('../Conte ...

The react-places-autocomplete feature is causing the components below to be shifted downward

For a while now, I've been facing an issue where using the example provided in the latest README.md GitHub repository is causing the components below to be pushed down, resulting in a less than ideal user experience. To illustrate this problem, I have ...

Setting the parent's height to match one of its children

I'm struggling to align the height of the pink '#images-wrap' with the main image. When there are too many small rollover images on the right, it causes the pink div to extend beyond the main image's height. If I could make them match i ...

Using Firebase Admin or the regular Firebase with Next.js

Currently, I am working on a project using Next.js and integrating Firebase. I have been successfully fetching data in my components using the Firebase package designed for frontend use. However, I recently attempted to utilize Firebase within getServerS ...

Increasing the height of a jQuery div element and displaying image captions when hovering over them

There is a mysterious 3px gap between the image and the overlay, causing the overlay to extend 3px beyond the height of the image. Switching the CSS to use bottom:3px fixes the issue, but it feels like a hacky solution. The source of this spacing conundrum ...

Having trouble incorporating a variable into a jQuery selector

Trying to crack this puzzle has been an ongoing battle for me. I seem to be missing something crucial but just can't pinpoint what. I recently discovered that using a variable in the jQuery selector can make a significant difference, like so: var na ...

Flowplayer playlist stops after playing the first clip

I am having issues with my flowplayer configuration, as it is not behaving as I expected. After the first video ends, I want the second and subsequent videos to play automatically. Can anyone provide some guidance on how to achieve this? $f("player", "/fl ...

Exposing the full binary in jQuery

Can anyone explain how jQuery can display the entire binary representation of a number without removing the leading zeros? Here is the code snippet: HTML: <input id="input" type="text" size="20"> <input id="result" type="text" size="30"> < ...

Execute multiple AJAX calls to continuously update the results for the end user

I am looking to implement a technique using AJAX and PHP to constantly update the browser results. The goal is to dynamically add HTML files to a designated div with the ID results, each representing one of 21 different cities. Rather than displaying all c ...

Creating dynamic buttons with event listeners and parameters in JavaScript using jQuery

I am attempting to dynamically create and append buttons to an HTML page with defined events using the following code: var mdata = JSON.parse(data); mdata.forEach(function(k) { $("#routesPage").append("<button class='accordion' onclick=&a ...

What is the best way to pass a VueJS object to be stored in a Laravel controller?

I am facing an issue with my methods where the data is not getting stored in the database. I am unsure why the information is not being sent to the controller. Even though I input the correct data, it fails to load into the database. However, it does pass ...

transferring information to d3.js

I have a json object structured in the following way { "tweet":[ {"text": "hello world"}, {"text": "hello world"} ] } When I check the console output of "data" in my code below, it shows me an Object tweet: Array[131]. However, when I l ...

Utilize the content within an input field to perform a calculation and showcase the outcome in a separate element

Currently, my shopping cart displays a price, quantity, and subtotal field for each product. While the user can change the quantity field, the other fields remain static. I am looking for a method to automatically calculate the subtotal whenever the user ...

What is the best way to incorporate the PUT method...?

Within the realm of programming, there exist three distinct files with specific roles - profiles.model.js, profiles.controller.js, and profiles.router.js. The focus now shifts towards implementing the PUT method across these three files. To begin, profiles ...

Deactivating a form field depending on a selected radio button in Angular 2

If I have two radio buttons, with a click function called localClick for the first button to give value 1 and the second button to give value 2. <div class="ui-g-12"><p-radioButton name="group1" value="Local" (click)=localClick(1) label="Local"&g ...

Is there any specific reason not to use a short HTML/CSS syntax like <div a b c></div>?

When it comes to writing HTML in less standard environments, such as a phonegap app where strict syntax and semantics are not crucial, I have developed a unique approach that works for me. I aim to keep my HTML code short and concise by using the followin ...

What sets apart local and global variables when it comes to JavaScript?

It has come to my attention that in the realm of JavaScript, there are instances where a variable is created within a function without explicitly declaring it with var. For instance: function myfunction() { x = 10; var y = 10; } What sets these ...

Tips on rotating a 3D shape using axis in three.js

Help needed with rotation in three.js I am facing a challenge when trying to rotate a 3D cube in one of my games. //initialize geometry = new THREE.CubeGeometry grid, grid, grid material = new THREE.MeshLambertMaterial {color:0xFFFFFF * Math.random(), sha ...