Ir al contenido

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...

0views

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.).

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
//(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');
// 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 CSS
jugador.style.setProperty('left', `${posicioX}px`); //Afegir o modificar una propietat CSS
jugador.style.setProperty('top', `${posicioY}px`);
jugador.style.getPropertyValue('left'); //Obtenir el valor d'una propietat CSS
vectorEnemic[0].style.removeProperty('box-shadow');
vectorEnemic[0].style.backgroundColor = 'red'; //Mètode antic, vàlid però s'ha de fer servir camelCase

Class 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 classe
projectil.classList.remove('actiu'); // Eliminar una classe
boss.classList.toggle('superpoder'); //Sinó existeix l'afegeix i si existeix l'elimina
jugador.classList.contains('estilsJugador'); //Comprova si existeix la classe a la llista

Attribute Modification (getAttribute, setAttribute, removeAttribute, hasAttribute and toggleAttribute)

Sección titulada «Modificación de Atributos (getAttribute, setAttribute, removeAttribute, hasAttribute y toggleAttribute)»
// Afegir o eliminar atributs
jugador.getAttribute('src'); //Obtenir l'atribut d'un element
jugador.setAttribute('src', './naus/starfighter.webp'); //Afegeix o modifica un atribut
jugador.hasAttribute('src'); // Comprovar si existeix l'atribut
jugador.toggleAttribute('id', 'nauAmbEscut'); //Ex: mostrar un shadow brillant amb CSS
jugador.removeAttribute('id');

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 DIV
pantalla.append(enemic); // Afegeix l'element DIV al final del contenidor "pantalla"
enemic.remove(); // Elimina l'element DIV

Examples 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 DOM
function 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 DOM
function 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);
}