0

Most of the HTML in my web app is dynamically generated: I take an object and create a grid row for instance, something like this:

var TheHTML = TheHTML + '<div class="HiddenDiv">' + SomeObject.ID + '</div>';
TheHTML = TheHTML + ....
$('#SomeTableContainer').html(TheHTML);

That way, when the user clicks on that row, I can access the ID of the object represented on the row using .find('.HiddenDiv')

How can I instead use .data() to insert the ID of the object to the row and later retrieve it without reading the ID from the DOM?

Thanks.

17
  • 1
    I don't get it, are you really redeclaring the same variable on every line (try +=)? Anyway, $(TheHTML).data('ID', SomeObject.ID); Commented Nov 3, 2012 at 4:01
  • I'm first generating all the HTML and THEN I'm inserting the final string into the HTML, only once. And yes, doing var TheHTML = TheHTML + is actually the fastest way to do it because browsers became optimized for that. I tested that on jsperf and that's the fastest method. Commented Nov 3, 2012 at 4:06
  • @frenchie do it in object way Commented Nov 3, 2012 at 4:06
  • @frenchie, I believe he meant you could use ThenHTML += '<div ....>'; instead of repeating the Variable after the equal sign. Of course that means you should also drop the var declaration. Commented Nov 3, 2012 at 4:08
  • 1
    @frenchie - Are you saying browsers are optimized for you declaring the same variable over and over instead of just adding to it? If so please, pretty please, show me the documentation on that ! Commented Nov 3, 2012 at 4:09

1 Answer 1

2

custruct DOM in object way:

$('#SomeTableContainer').children().remove();

var TheHTML=($('<div>')
   .append($('<div>').html('my subdiv div').data('subid',1))
   .append($('<div>').html('my subdiv div1').data('subid',2))
);
TheHtml.data('id',id);
TheHtml.bind('myevent',function(e){console.log($(this).data('id'));});
$('#SomeTableContainer').append(TheHTML);
Sign up to request clarification or add additional context in comments.

6 Comments

he's using .find() so I think he wants to add IDs to the INNER Divs.
That's geat! Your solution is actually way classier than mine. :D
When creating an element, you can actually do : $('<div />', {html: 'my subdiv div1'}).data('subid',2);
Well anyway, looks like doing it this way is better in code but worse in terms of performance. Thanks for your input, it clarified the deal.
@frenchie, just take care when you worry so much about performance. A project has to be mantainable. Lotus worried about performance, Microsoft trusted Moore's Law and launched a "bloated" Excel. You know who won. ^^
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.