01. DOM Manipulation
The DOM is the representation of an HTML document. This can be visualized as a tree of elements or nodes. Browsers provide an API...
01. The Document Object Model (DOM)
Sección titulada «01. El Document Object Model (DOM)»The DOM is the representation of an HTML document. This can be visualized as a tree of elements or nodes. Browsers provide an API to interact with the DOM's HTML elements using JavaScript. These interactions allow for dynamic modification of the HTML structure, CSS styles, and document content. They also allow responses to user-generated events (clicks, mouse movements, keyboard inputs, etc.).
Dynamic DOM Manipulation
Sección titulada «Manipulación dinámica del DOM»When the webpage loads, we will generate the DOCUMENT object that will store all the HTML content of the webpage. With Javascript, we will be able to access its methods and properties to interact with the page elements.
On HTML elements, we will be able to perform the following actions:
- We will select elements
- We will modify the existing elements
- The content
- CSS styles
- Attributes and classes
- We will add new elements
- We will remove existing elements
1. Element Selection
Sección titulada «1. Selección de Elementos»//(querySelector) Seleccionar un únic element HTML (si hi ha diversos iguals escull el primer)const jugador = document.querySelector('#jugador');
// (querySelectorAll) Seleccionar un conjunt d'elements HTML i els recull en un vector (Array).const vectorEnemics = document.querySelectorAll('.enemic');2. Element Modification
Sección titulada «2. Modificación de Elementos»Content Modification (textContent)
Sección titulada «Modificación del Contenido (textContent)»// Modificar contingut HTML (mètode molt utilitzat i insegur si és mostren dades introduïdes per l'usuari)divNomUsuari.innerHTML = `<p>Nom: ${nomUsuari}</p>`;
// Modificar el contingut de text d'un element (mètode segur)divNomUsuari.textContent = `Nom: ${nomUsuari}`;divNivell.textContent = `Nivell: ${nivell}`;Style Modification (style with setProperty, getProperty, and removeProperty)
Sección titulada «Modificación de Estilos (style con setProperty, getProperty y removeProperty)»// Modificar estils CSSjugador.style.setProperty('left', `${posicioX}px`); //Afegir o modificar una propietat CSSjugador.style.setProperty('top', `${posicioY}px`);jugador.style.getPropertyValue('left'); //Obtenir el valor d'una propietat CSSvectorEnemic[0].style.removeProperty('box-shadow');vectorEnemic[0].style.backgroundColor = 'red'; //Mètode antic, vàlid però s'ha de fer servir camelCaseClass Modification (classList with add, remove, toggle, and contains)
Sección titulada «Modificación de Clases (classList con add, remove, toggle y contains)»jugador.classList.add('estilsJugador'); // Afegir una classeprojectil.classList.remove('actiu'); // Eliminar una classeboss.classList.toggle('superpoder'); //Sinó existeix l'afegeix i si existeix l'eliminajugador.classList.contains('estilsJugador'); //Comprova si existeix la classe a la llistaAttribute Modification (getAttribute, setAttribute, removeAttribute, hasAttribute and toggleAttribute)
Sección titulada «Modificación de Atributos (getAttribute, setAttribute, removeAttribute, hasAttribute y toggleAttribute)»// Afegir o eliminar atributsjugador.getAttribute('src'); //Obtenir l'atribut d'un elementjugador.setAttribute('src', './naus/starfighter.webp'); //Afegeix o modifica un atributjugador.hasAttribute('src'); // Comprovar si existeix l'atributjugador.toggleAttribute('id', 'nauAmbEscut'); //Ex: mostrar un shadow brillant amb CSSjugador.removeAttribute('id');3. Creation and Deletion of Elements
Sección titulada «3. Creación y Eliminación de Elementos»We will create Elements, add them to the DOM, and delete them (createElement, append and remove)
Sección titulada «Crearemos Elementos, los Agregaremos al DOM y los Eliminaremos (createElement, append y remove)»// Crear un nou element, afegir-lo al DOM i eliminar-lo.const enemic = document.createElement('div'); // Crea l'element DIVpantalla.append(enemic); // Afegeix l'element DIV al final del contenidor "pantalla"enemic.remove(); // Elimina l'element DIVExamples of how we will create elements, add them to the DOM, and delete them.
//Exemple funció crear per crear un element i afegir-lo al DOMfunction crearEnemic(x, y) { const enemic = document.createElement('div'); enemic.classList.add('enemic'); enemic.style.left = `${x}px`; enemic.style.top = `${y}px`; pantalla.append(enemic); //Amb "prepend" l'afegiria al principi del contenidor "pantalla" return enemic;}
let posicioX = 500;let posicioY = 100;const primerEnemic = crearEnemic(posicioX, posicioY); //Crear l'enemic i obtenir la referència per la seva gestió
// Eliminar un element del DOMfunction eliminarEnemic(enemic, posicioX) { if (posicioX <= 0) { enemic.remove(); } else { posicioX -= 10; enemic.style.left = `${posicioX}px`; }}
for (let i = 0; i < 50; i++) { eliminarEnemic(primerEnemic, posicioX);}
