write them as a long string and put them in a document using the appropriate jQuery function. Something like:
The problem with this approach is that you will need a multi-line string - Javascript does not support, so in fact you will get:
elem.html( '<div class="wrapper">'+ '<div class="inner">'+ '<span>Some text<span>'+ '</div>'+ '<div class="inner">'+ '<span>Other text<span>'+ '</div>'+ '</div>');
Using the method you suggested above is about as clean as I could get it:
elem.append( $('<div/>', {'class': 'wrapper'}).append( $('<div/>', {'class': 'inner'}).append( $('<span/>', {text: 'Some text'}) ) ) .append( $('<div/>', {'class': 'inner'}).append( $('<span/>', {text: 'Other text'}) ) ) );
Another advantage of this is that you can (if you wish) get direct links to each newly created element without re-querying the DOM.
I like to write polyglots , so to make my code re-accessible, I usually do something like this (since jQuery .html() doesn't support XML):
// Define shorthand utility method $.extend({ el: function(el, props) { var $el = $(document.createElement(el)); $el.attr(props); return $el; } }); elem.append( $.el('div', {'class': 'wrapper'}).append( $.el('div', {'class': 'inner'}).append( $.el('span').text('Some text') ) ) .append( $.el('div', {'class': 'inner'}).append( $.el('span').text('Other text') ) ) );
This is not very different from method # 2, but it gives you more portable code and does not rely on innerHTML internally.
lucideer Jun 23 2018-12-12T00: 00Z
source share