I need to be able to dynamically generate (and insert into the DOM) HTML elements that are quite sizeable such as the snippet below:
<div class="messageToAndFromOtherMember" id="13">
<span>the message</span>
<span>2012-12-02 14:05:45.0</span>
<span>sent</span>
<input type="checkbox" value="13" id="listOfMessagesForDeletion3" name="listOfMessagesForDeletion">
<input type="hidden" name="_listOfMessagesForDeletion" value="on">
</div>
As of now I am not sure how to go about building such a large DOM element and do it following jQuery best practises. What I do now is simply concatenate a string as follows (which is quite ugly…):
$("#latestMessages"+" "+"div[id^='"+response.senderId+'.'+response.recipientId+"'], #latestMessages"+" "+"div[id^='"+response.recipientId+'.'+response.senderId+"']").replaceWith("<div id='"+latestMessageId+"'><span>"+response.message+"</span><span>SENT</span><span><a href='"+response.recipientId+"'>ma conversation avec "+response.recipientId+"</a></span></div>");
I would be very grateful if someone could suggest a better way of building the DOM element.
You can select the child elements and apply your response data to them rather than concatenation. I presume there may be more than one message given the context of your snippet. In this case you can use templating to append each subsequent message div. I prefer the native template engine in knockoutjs for this, http://knockoutjs.com/ . There are plenty of other jquery templating solutions:
https://stackoverflow.com/search?q=jquery+templating