I have seen a video tutorial on creating and appending content to the DOM. He suggests that wrting a string like so:
jQuery('<h2 class=myClass>Hello world</h2>').appendTo('article');
is sloppy compared to creating an object like so:
jQuery('<h2></h2>', {text: 'Hello world', class 'myClass'}).appendTo('article');
I’m still a little unconvinced that this is the best way of doing this. For example, I have a slightly more complex example of DOM creation here:- http://jsperf.com/string-creation-dave Using the suggested method of creating the elements in JS performs alot slower than passing a string of the whole element.
Therefore, is the only benefit of creating the objects with JS readability? How do you create elements in JS? Do you just pass through strings to be inserted into the DOM or do you generate the objects in JS and build up the objects that way?
The cleanest solution is to create the Elements via the
createElementMethod, set its Attributes and insert it into the dom afterwards.If you have more elements you build the according tree and insert the whole tree into the dom when you are finished.
example from MDN:
but serious, who wants to write such code;) Personally I’d stick with your first example, whatever suits you.