Using jquery is it better to create a DOM element like this:-
function create(options) { $('<form action="' + options.action + '"></form>'); }
Or like this:
function create(options) { $form = $('<form></form>'); $form.attr('action',options.action); }
This may be a matter of opinion. I feel that the second way gives more clarity but I suspect it is less efficient...
To add a new element to the HTML DOM, you must create the element (element node) first, and then append it to an existing element.
The createElement() method creates an element node.
As for performance: InnerHTML is most definitely going to be slower, because it needs to be parsed and internally converted into DOM elements (maybe using the createElement method).
Check this to find out for your self.
Note higher is better (OPS/Sec = operations per second = how many times per second the given code executes)
And the test winner in every other browser than Opera:
var form = document.createElement("form"), $form = $(form); form.action = options.action;
NOTE:
the native method will be even faster if you don't need a jQuery object:
var form = document.createElement("form"); form.action = options.action;
jQuery can create object as following code
$form = $('<form>', {action: 'my action'});
class
is a reserved word in IE and needs to be quoted. See full list of reserved words: Reserved Keywords in Javascript
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With