Good practices when creating elements with jQuery

8

When I need to create elements in the DOM using jQuery, I usually use the following syntax:

$('<div>').addClass('minha-div').attr({id: 'id-da-div'});

However, what I usually see in online tutorials is a bit different. Usually it is:

$('<div></div>').addClass('minha-div').attr({id: 'id-da-div'});

Or:

$('<div id="id-da-div" class="minha-div"></div>');
asked by anonymous 17.07.2014 / 14:16

2 answers

9

You should rather close the div:

  

"To ensure cross-platform compatibility, the snippet must be well-formed."    link

As for the second question, I think it does. If it's not constants I'd rather use it the first way. It seems the latter is faster ( link )

    
17.07.2014 / 15:06
7

You can also use this:

$('<div>', {
    id: 'minhaDiv',
    class: 'minhaClasse',
    'outro-atributo': 'meuValor'
}).appendTo('body');

I always use it, it works perfectly!

    
17.07.2014 / 19:16