Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to create new DOM elements [closed]

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...

like image 878
rgvcorley Avatar asked Feb 23 '12 14:02

rgvcorley


People also ask

How do I add elements to my DOM?

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.

Which function in DOM allows you to create a new element?

The createElement() method creates an element node.

Is innerHTML faster than createElement?

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).


Video Answer


2 Answers

Check this to find out for your self.

Creating DOM notes using jQuery 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; 
like image 104
Andreas Louv Avatar answered Sep 18 '22 13:09

Andreas Louv


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

like image 22
komelgman Avatar answered Sep 21 '22 13:09

komelgman