yossi yossi - 1 year ago 67
Javascript Question

Creating native dom element, with data that jQuery's data() will use

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
won't work since I need complex data.

Answer Source

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")
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download