I also suggest using a function, my approach is much similar to other function-based approaches, but involves creating elements with their various attributes, rather than treating HTML as a string (both ways of working and the HTML-as-string approach are certainly more concise )
This approach, however, in my experience, makes it easier to make changes to the output without worrying about whether your HTML line is properly closed and escaped:
function prependNewPost(elem, stream) { var outerDiv = $('<div />', { 'id': stream.sid, 'class': 'row stream-posts' }), innerDiv = $('<div />', { 'class': 'span1 stream-thumb' }).appendTo(outerDiv), ul = $('<ul />', { 'class': 'thumnails' }).appendTo(innerDiv), li = $('<li />').appendTo(ul), a = $('<a />', { 'href': '#' }).appendTo(li), image = $('<img />', { 'src': 'http://placehold.it/60x60', 'alt': '' }).appendTo(a), secondInnerDiv = $('<div />', {'class' : 'span5 stream-content'}).appendTo(outerDiv); var p = $('<p />').text(stream.text).appendTo(secondInnerDiv); outerDiv.prependTo(elem); } $('#add').click( function() { var stream = {}; stream.sid = 'two'; stream.author = 'Geoff'; stream.text = 'Some text, a pseudo-Lorem ipsum, if you will...'; prependNewPost($('#stream'),stream); });
JS Fiddle demo .
Literature:
source share