Good practices when creating elements with jQuery

Asked

Viewed 10,723 times

8

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

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

However, what I usually see in Internet tutorials is a little different. Is usually:

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

Or:

$('<div id="id-da-div" class="minha-div"></div>');
  • I wonder if, because I didn’t close the div in the first example, there could be some problem (until today it worked correctly) and if this is bad practice.

  • I must create the attributes by the functions of jQuery (as in the first and second example) or I must "write it" directly into the argument where I pass the selector (third example)?

2 answers

8


  • Thank you! you took away all my doubts.

  • 1

    For the second question, personally I find it more elegant and practical through a JSON (first two examples) than a giant, unidentifiable and possibly difficult to interpret string.

7

You can also use as follows:

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

I always use it like this, it works perfectly!

  • I had never used this syntax until a few months ago. Personally I found it a little more complicated than when you already have the element created in the DOM, but it is a matter of getting used to.

  • This passage of objects in the second parameter was much better than any of my examples. As soon as possible, I will refactor my codes :)

  • Very nice. Like this $('<div></div>', {html: 'conteúdo da div'}) you write inside her!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.