Ad

If I Have A List Of DOM Elements That Need To Be Appended, Is There A Way To Combine Them First Before Appending?

- 1 answer

Given the following code:

li = random_object["li_element"] 
other = other_object["p_element"]
...
// I have a bunch of objects above, all of which were initially created and stored as jQuery objects, e.g.,
// random_object["li_element"] = $("<li>test</li>")

$("#target").append(li)
$("#target").append(other)

I understand that .append() is an expensive method, so I'm wondering is there a way to first combine the elements above, li and other, in that order, and then append them all at once?

Ad

Answer

Yes, both in jQuery and when using the DOM directly.

Using jQuery

You can create a jQuery object using the signature accepting an array wrapping those two elements and then append it:

$("#target").append($([li[0], other[0]]));

The [0] there are to put the raw elements, not the jQuery objects, in the array. $() accepts an array of DOM elements, but not jQuery objects. If those jQuery objects may have multiple elements in them, you need to do a bit more work. Using ES2015+:

$("#target").append($([...li.get(), ...other.get()]));

Using ES5 only:

var array = li.get();
array.push.apply(array, other.get());
$("#target").append($(array));

Live Example:

var li = $("<li>li</li>");
var other = $("<li>other</li>");
$("#target").append($([li[0], other[0]]));
<ul id="target"></ul>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Using the DOM directly

With the DOM, you can create a document fragment and append it:

var fragment = document.createDocumentFragment();
fragment.appendChild(li[0]);
fragment.appendChild(other[0]);
document.getElementById("target").appendChild(fragment);

The contents of the fragment are appended, not the fragment itself.

Again the [0] are so we access the raw DOM elements instead of the jQuery objects. And again, if there are multiple elements in li and/or other, you need to handle that:

var fragment = document.createDocumentFragment();
li.each(function() {
    fragment.appendChild(this);
});
other.each(function() {
    fragment.appendChild(this);
});
document.getElementById("target").appendChild(fragment);

Live Example:

var li = $("<li>li</li>");
var other = $("<li>other</li>");
var fragment = document.createDocumentFragment();
fragment.appendChild(li[0]);
fragment.appendChild(other[0]);
document.getElementById("target").appendChild(fragment);
<ul id="target"></ul>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

I understand that .append() is an expensive method

Not especially, but if you had some seriously-performance-critical code and a lot of things to append, building them up in a fragment and then appending the fragment does reduce the overhead.

Ad
source: stackoverflow.com
Ad