I need to copy data values from one element to another, but jQuery's clone() method doesn't clone the data. And I can't iterate over the data either:
element.data().each
because data()
is a function and not a jQuery object. It seems I have to keep a separate list of attribute names and reference those but that seems too hacky. So how can I do either of these:
a) Iterate over data items
OR
b) clone()
an element with its data.
The clone() is an inbuilt method in jQuery which is used to make a copy of selected elements including its child nodes, text and attributes. Syntax: $(selector).clone(true|false) Parameter: It accepts an optional parameter which could be either true or false specifies that event handler should be copied or not.
First, select the div element which need to be copy into another div element. Select the target element where div element is copied. Use the appendTo() method to copy the element as its child.
To clone an element using jQuery, use the jQuery. clone() method. The clone() method clones matched DOM Elements and select the clones. This is useful for moving copies of the elements to another location in the DOM.
To really only copy the data-*, this is quite straightforward:
$(destination).data( $(source).data() );
This is because using .data() no arguments will return a key-value object of all pieces of data and vice versa you can also update multiple pieces data at once using a key-value object.
UPDATE 25th May 2017
A clever alternative in JavaScript without jQuery appears to be:
Object.assign(destination.dataset, source.dataset);
Answer to:
a) Iterate over data items
$.each(element.data(), function (name, value) { // ... do something })
If element is a DOM element, use this:
$.each($.data(element), function (name, value) { // ... do something })
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With