What is the best way to create elements and add them to dom in jquery?

Let's say I add li elements to javascript code with jQuery.

Example 1:

for(var i=0 i<=5; i++){ var li = $("<li/>"); li.html("teest "+i); $("#ulid").append(li); } 

I found out that the above example is bad practice due to the fact that the loop rebuilds the dom every time it reaches append (li).

If so, what is the best way to do the same as in the above example?

+6
source share
3 answers

What you are doing is probably great for the vast majority of use cases. Your code will ultimately call the DOM function appendChild once for each li , and I'm sure that all answers will still be doing. And again, this is probably good, although it can cause melting every time.

In those situations where you absolutely need to not have to duplicate the DOM on each pass through the loop, you probably need a piece of the document .

 var i, li, frag = document.createDocumentFragment(); for(i=0; i<=5; i++){ li = $("<li>" + "teest "+i + "</li>"); frag.appendChild(li[0]); } $("#ulid").append(frag); // Or $("#ulid")[0].appendChild(frag); 

When you add a fragment, the children of the fragment are added, not the actual fragment. The advantage is that, being the only DOM call, you give the DOM engine the ability to add all the elements and only pay at the end.

+9
source

You can include internal HTML in the append text, as well as several elements at a time, so just create one large line and add it only once.

 var append_text = ""; for (i = 0; i <= 5; i++) { append_text += "<li>test " + i + "</li>"; } $("#ulid").append(append_text); 
+8
source

The jQuery.append method accepts arrays of elements, so you can do this:

 var elems = []; for(var i=0; i<=5; i++){ var li = $("<li/>"); li.html("teest "+i); elems.push(li[0]); // Note we're pushing the element, rather than the jQuery object } $("#ulid").append(elems); 
+8
source

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


All Articles