Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I copy the data of an element with jQuery? [duplicate]

Tags:

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.

like image 494
MDCore Avatar asked Oct 07 '08 10:10

MDCore


People also ask

What is clone in jQuery?

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.

How do you copy the content of a div into another div using jQuery?

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.

How do you get a copy of an object using jQuery?

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.


2 Answers

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); 
like image 58
Nexii Malthus Avatar answered Oct 18 '22 12:10

Nexii Malthus


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 }) 
like image 20
DUzun Avatar answered Oct 18 '22 12:10

DUzun