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

163 Views Asked by At

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.

2

There are 2 best solutions below

5
adeneo On BEST ANSWER

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>

1
Stuart On

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");