Documento HTML DOM createDocumentFragment()
Ejemplos
Añadir elementos a una lista vacía:
const fruits = ["Banana", "Orange", "Mango"];
// Create a document fragment:
const fragment = document.createDocumentFragment();
// Add li elements to the fragment:
for (let x in fruits) {
const li = document.createElement('li');
li.textContent = fruits[x];
dFrag.appendChild(li);
}
// Add fragment to a list:
document.getElementById('myList').appendChild(fragment);
Agregar elementos a una lista existente:
const fruits = ["Banana", "Orange", "Mango"];
// Create a document fragment:
const fragment = document.createDocumentFragment();
// Add li elements to the fragment:
for (let x in fruits) {
const li = document.createElement('li');
li.textContent = fruits[x];
dFrag.appendChild(li);
}
// Add fragment to a list:
document.getElementById('myList').appendChild(fragment);
Definición y uso
El createDocumentFragment()
método crea un nodo fuera de la pantalla.
El nodo fuera de pantalla se puede usar para crear un nuevo fragmento de documento que se puede insertar en cualquier documento.
El createDocumentFragment()
método también se puede utilizar para extraer partes de un documento, cambiar, agregar o eliminar parte del contenido e insertarlo nuevamente en el documento.
Nota
Siempre puede editar elementos HTML directamente. Pero una mejor manera es construir un fragmento de documento (fuera de pantalla) y adjuntar este fragmento al DOM real (en vivo) cuando esté listo. Debido a que inserta el fragmento cuando está listo, solo habrá un reflujo y un solo renderizado.
Si desea agregar elementos de elementos HTML en bucles, el uso de fragmentos de documentos también mejora el rendimiento.
¡Advertencia!
Los nodos de documento adjuntos al fragmento de documento se eliminan del documento original.
Sintaxis
document.createDocumentFragment()
Parámetros
NINGUNA |
Valor devuelto
Escribe | Descripción |
Nodo | El nodo DocumentFragment creado. |
Compatibilidad con navegador
document.createComment()
es una característica DOM Nivel 1 (1998).
Es totalmente compatible con todos los navegadores:
Chrome | IE | Edge | Firefox | Safari | Opera |
Yes | 9-11 | Yes | Yes | Yes | Yes |