JQuery: add separately or immediately + selector?

I create a jQuery UI widget, and when I initialize, I create several div, anchors, input. I read that it’s faster to create an entire HTML string and then add it to the DOM than to add every single DOM element.

However, I need access to these elements later, so I also tend to create them individually and then add them, so I already have caching, and not selecting them after adding all the HTML.

What is going faster?

eg:.

var html = $('<div id="container">.....several more divs, anchors and inputs all with IDs......</div>');

<dom element>.append(html);
this.container = $('#container');
this.search = $('#search');
...and so on

or

this.container = $('<div id="container"></div>');
this.search = $('<input .... id="search" />');
...and the rest of the divs, anchors and inputs then...

<dom element>.append(this.container).append(this.search) ..... and so on
+3
source share
2 answers

I also suggest reading these two blogs.

43,439 reasons to use append () correctly

5 , jQuery

+4

DOM, , .

var html = $('<div id="container">.....several more divs, anchors and inputs all with IDs......</div>');

, , , .

this.container = html; //since #container is the top div in html, html = #container
this.search = html.find('#search');

, , DOM , .

<dom element>.append(html);

, , DOM, .

0

Source: https://habr.com/ru/post/1724653/


All Articles