Reputation: 1492
I am creating a jQuery plugin which generates a lot of divs
.
Initially i was creating all the elements using append
function as below.
var myObject= $('<div></div>').addClass('myobjectname');
parentObject.append(myObject);
I have lot of elements created like this and also each have different data
associated with them using myObject.data('mykey',ajavascriptobject);
But later on, when I started reading more about optimization of jQuery, I understood that DOM manipulation functions like append
are very costly when it comes to performance.
Now, I am trying to create the whole div
structure as string and then append it as a whole to the parent DOM object which is supposed to very much improve the performance.
var i=0;
var myBigString = [];
myBigString[i++] = "<div class=\"myobjectname\">";
myBigString[i++] = "my content";
myBigString[i++] = "</div>";
parentObject.append(myBigString.join(''));
I am using the data()
function to store details about each object to later access it (when clicking/mouseover etc). But now, since I am creating a string of the whole div
structure,
How can I associate the data
to the elements if I am creating them as a string and later appending it to DOM?
Upvotes: 2
Views: 111
Reputation: 29498
You do it like this:
<div data-datum-name="your data string"></div>
For objects:
<div data-datum-name=' + JSON.stringify(yourObject) + '></div>
Upvotes: 2