2

I'd like to create a DOM element, natively, attaching data to it. and than, later, create a jQuery element of it, setting (automatically) these data to be available through the data() function.

var x = document.createElement("div");
x. ???? // add the data {a: {x: 4, y:6}}
x = $(x);
var obj = x.data("a")
console.log(a.x); // getting '4'

can it be done - and how?

please note that data-[attrib-name] won't work since I need complex data.

yossi
  • 3,090
  • 7
  • 45
  • 65

2 Answers2

2

You can use $.data() to set data on a native DOM node in jQuery

var x = document.createElement("div");

$.data(x, 'a', {x: 4, y:6});


x = $(x);
var obj = x.data("a")
console.log(obj);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
adeneo
  • 312,895
  • 29
  • 395
  • 388
  • great answer, thanks. however i cant save ref' to objects with it. any idea how to solve that? – yossi Nov 20 '16 at 13:39
  • @yossi - native data attributes **can't** store objects at all, **only** strings. jQuery on the other hand lets you store complex objects by storing them in memory, in a special object jQuery keeps for associated data, that's why it can store objects in `$.data`. If you wan't to store objects in `$.data` you **have** to create the elements with jQuery. – adeneo Nov 20 '16 at 13:44
  • OK. Can i access (trying to find it for the last hour) the memory object and set the data "manually"? – yossi Nov 20 '16 at 13:46
  • 1
    Actually, yes you can, give me a second to demonstrate, – adeneo Nov 20 '16 at 13:48
  • Edited the answer to show how to add `$.data` to a native DOM node – adeneo Nov 20 '16 at 13:50
1

You can set the data attribute, by using javascript's setAttribute() like so:

var theDiv = document.createElement("div");
theDiv.setAttribute('data-x', '4');
theDiv.setAttribute('data-y', '6');

Access them:

console.log(theDiv.getAttribute('data-y'));

And also access the same with jQuery:

$(theDiv).data("x");
Stuart
  • 6,630
  • 2
  • 24
  • 40