DWEC

Logo

Desenvolupament web en entorn client (DAW)

View the Project on GitHub jrodr236/DWEC

Creació i navegació pels nodes DOM

Teoria completa

DOM tree

Podem navegar per l’arbre del DOM utilitzant les relacions entre els nodes.

Relacions entre els nodes

<html>

  <head>
      <title>DOM Tutorial</title>
  </head>

  <body>
      <h1>DOM Lesson one</h1>
      <p>Hello world!</p>
  </body>

  <script>
    
  </script>

</html>

Obrir Console (F12):

document;

document.firstElementChild;

document.firstElementChild.firstElementChild;

document.firstElementChild.firstElementChild.nextElementSibling;

document.firstElementChild.firstElementChild.nextElementSibling.firstElementChild;

document.firstElementChild.firstElementChild.nextElementSibling.firstElementChild.nextElementSibling;

Nodes

Teoria completa

Creant nous elements HTML (nodes):

<!DOCTYPE html>
<html>
<body>

<div id="div1">
<p id="p1">This is a paragraph.</p>
<p id="p2">This is another paragraph.</p>
</div>

<script>
var para = document.createElement("p");
var node = document.createTextNode("This is new.");
para.appendChild(node);
var element = document.getElementById("div1");
element.appendChild(para);
</script>

</body>
</html>

demo

Explicació

Altres operacions

També és possible:

Col·leccions

Teoria completa

L’objecte HTMLCollection

El mètode getElementsByTagName() retorna un objecte HTMLCollection.

Un objecte HTMLCollection és com un array list (col·lecció) d’elements HTML.

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript HTML DOM</h2>

<p>Hello World!</p>

<p>Hello Norway!</p>

<p id="demo"></p>

<script>
var myCollection = document.getElementsByTagName("p");
document.getElementById("demo").innerHTML =
"The innerHTML of the second paragraph is: " +
myCollection[1].innerHTML;
</script>

</body>
</html>

demo

La longitud (lenght) de l’HTMLCollection

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript HTML DOM</h2>

<p>Hello World!</p>

<p>Hello Norway!</p>

<p>Click the button to change the color of all p elements.</p>

<button onclick="myFunction()">Try it</button>

<script>
function myFunction() {
    var myCollection = document.getElementsByTagName("p");
    var i;
    for (i = 0; i < myCollection.length; i++) {
        myCollection[i].style.color = "red";
    }
}
</script>

</body>
</html>

demo

HTMLCollection no és un array!

HTMLCollection pot semblar un array, però no ho és.

Pots recòrrer a la llista i referir-te als elements amb un número (igual que un array).

Però no pot utilitzar els mètodes dels arrays com valueOf(), pop(), push(), o join() en un HTMLCollection.

Llistes de nodes

Teoria completa

Els objectes NodeList son molt semblants als objectes HTMLCollection.

Alguns navegadors antics retornen un objecte NodeList enlloc d’un HTMLCollection en determinats mètodes.

També hi han mètodes que retornen NodeList en tots els navegadors.

Veure l’apartat corresponent de w3schools si cal més informació.