You don't have access to this class

Keep learning! Join and start boosting your career

Aprovecha el precio especial y haz tu profesión a prueba de IA

Antes: $249

Currency
$209
Suscríbete

Termina en:

1 Días
3 Hrs
51 Min
10 Seg

Navegación efectiva entre nodos

5/27
Resources

How to navigate the DOM hierarchically?

Navigating the Document Object Model (DOM) is an essential skill for any web developer. Understanding how to select elements hierarchically, whether they are parents, children or ancestors, can make manipulating the HTML document much easier. In this class, we will explore how to move through the DOM using different methods and properties.

How to select parent and child elements?

To start working with the DOM, we select an element using its ID, which makes it easy to identify a specific section of the HTML we want to work with. Suppose we are interested in a <ul> with a specific ID, and we want to analyze its child elements.

const parent = document.getElementById('parents');console.log(parent);

When we run this snippet, we get the element with all its children. This is useful when we want to manipulate or inspect a whole collection of nested elements.

How to access the first child of an element?

Sometimes we need to work exclusively with the first child of an element. In these cases, we can use firstElementChild, which gives us direct access to the node of the first child element.

const firstChild = parent.firstElementChild;console.log(firstChild);

This is especially useful when we want to manipulate or style only the first element of a list, leaving the others as is.

How to move between siblings in the DOM?

Understanding how to move between sibling nodes in the DOM can be particularly useful. We can use properties such as nextSibling and previousSibling to access the siblings of an element.

const nextSibling = parent.nextSibling;console.log(nextSibling);
const previousSibling = parent.previousSibling;console.log(previousSibling);

These properties can help us navigate to elements that are at the same hierarchical level within the DOM.

How to select an ancestor element?

Many times, it is necessary to go back in the DOM tree to find an ancestor element. The closest method allows us to accomplish this efficiently.

const grandParent = firstChild.closest('.menu');console.log(grandParent);

This is extremely useful when working with heavily nested elements, as closest will look for the closest ancestor element that matches the specified selector.

What are other ways to navigate the DOM?

In addition to the above methods, there are several other useful properties and methods you can employ to move through the DOM:

  • children: returns a collection of the child elements of a node.
  • childNodes: Returns all child nodes (including text and comment nodes).
  • lastChild: Returns the last child node of an element.
  • parentElement: Provides direct access to the parent element of a given node.

Trying these methods in different HTML structures will help you understand how the DOM works and will allow you to improve your ability to manipulate it.

How to practice navigating the DOM?

Practice is the key to improvement. I recommend you create exercises with varied HTML structures and experiment with the methods and properties we have discussed. By tackling different configurations and structures, you will gain confidence and skill in navigating the DOM.

So, let's get to work! Keep exploring and manipulating the DOM with these methods and you'll soon discover the endless possibilities that web development has to offer.

Contributions 27

Questions 3

Sort by:

Want to see more contributions, questions and answers from the community?

```js /* La navegación entre nodos recibe el nombre de traversing DOM, y consiste en recorrer los nodos basandonos en la jerárquia de padre, hijos, hermanos. */ //* Navegación del elemento padre a hijo const menu = document.querySelector('.menu') console.log(menu.children) /* children → nos retorna un HTMLCollection con los nodos hijos del nodo padre. */ //? Acceder al primer nodo → firstElementChild console.log(menu.firstElementChild.innerHTML) //? Acceder a un node específico → [] console.log(menu.children[1].innerHTML); //? Acceder al último elemento → lastElementChild console.log(menu.lastElementChild.innerHTML); //* Navegación de un nodo hijo a padre const link = document.querySelector('.link') /*parentElement → nos retorna su nodo padre */ console.log(link.parentElement) // Para conocer el abuelo de ese nodo podemos usar nuevamente parentElement y asi sucesivamente . console.log(link.parentElement.parentElement) //* Navegación entre nodos hermanos /* previousSiblind → Hermano anterior nextSibling → Hermano siguiente */ console.log(link) console.log(link.previousElementSibling.textContent) console.log(link.nextElementSibling.textContent) ```![Untitled](https://prod-files-secure.s3.us-west-2.amazonaws.com/519099cb-ab4b-4ace-83bd-688d8f9ee34e/b08c5ecb-a8f5-45e2-966d-970640b5d4ab/Untitled.png)
Si por alguna razonn no te sale ahi te comparto. ```js document.addEventListener('DOMContentLoaded', () => { const parent = document.getElementById("parent"); console.log(parent); const parentChildren = parent.children; console.log(parentChildren); const secondChild = parent.children[1]; // Cambiado a `children[1]` ya que `secondElementChild` no es válido console.log(secondChild); const lastChild = parent.lastElementChild; console.log(lastChild); const previousSibling = parent.previousElementSibling; console.log(previousSibling); const nextSibling = parent.nextElementSibling; console.log(nextSibling); }); ```
desde un entorno productivo, este tipo de selectores no son muy recomendados, ya que si modificas el html, terminarías seleccionando nodos que no necesitas! just getElementById is enough for almost every posible destiny
Por si a alguien le ayuda visualmente con el traversing DOM:![](https://static.platzi.com/media/user_upload/traversingDOM-4dd4ec25-67a8-40aa-817e-f7e99a79bd3c-75e509ad-7867-4a5a-a3bd-115780455254.jpg)
¿Cuál es la diferencia entre traer un nodo y traer un elemento?
Esto es valido para llamar a un hijo?? ` const parents = document.getElementById("parents");` `const children = parents.children;` `console.log(children);` `const firstChild = children[0];` `console.log(firstChild);`
Se me hace muy loco el como ciertas propiedades funcionan o dejan de funcionar si usas querySelector vs getElementsByClassName
![](https://static.platzi.com/media/user_upload/imagen-fe475919-f86c-4ef4-bda1-ac0a8f8656b1.jpg)![](https://static.platzi.com/media/user_upload/imagen-eb6f8537-27d2-4e31-9c27-99fa41677df0.jpg)
Honestamente me parece una broma hacia los estudiantes que se pongan a copiar y pegar codigo. Entiendo que en recursos está el github, pero no esta ordenado por cada clase, cada documento y carpeta tiene nombres difrentes a las clases. Si por falta de tiempo o lo que fuere no puede ponerse a escribir el codigo en la clase, lo ideal sería que pusiera el enlace directamente a los documentos que se usan en esta clase, y no el enlace a los documentos de TODO EL CURSO, por que ni siquiera estan ordenados por el nombre de la clase en la que se usa x documentos HTML o JS. Creo que seria una buena practica y un respeto hacia los estudiantes poner el enlace directo a los recursos que se usan en esta clase, principalmente por que mi tiempo es limitado para poder estudiar en Platzi y no puedo perderlo teniendo que buscar recursos en el Github que esta mal ordenado o directamente no se encuentran ahi, como es el caso del documento html de esta clase. Un saludo y tengan un buen dia :)
![](https://static.platzi.com/media/user_upload/image-e70bbabf-b490-41c5-b384-87d0a1a5ff9d.jpg)
Propiedades y métodos vistos hasta ahora: ![](https://static.platzi.com/media/user_upload/Arbol2-e76e631f-436e-4090-8cfa-3b2efe972ef8.jpg)
Propiedades y métodos vistos hasta ahora: ![](https://static.platzi.com/media/user_upload/Arbol-0d0d852c-a13f-4fdd-90f9-3e799ea94874.jpg)
Conclusión: ![](https://static.platzi.com/media/user_upload/Conclusion-56aa2318-0b68-44b8-8e79-34f896d91a7e.jpg)
Conclusión: ![](https://static.platzi.com/media/user_upload/Conclusion-9c54efc5-2723-4e65-aaf4-211b363db44e.jpg)
```html <html lang="es"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Consultando el DOM con getElementById y querySelector</title> </head> <body> <header> <h1 id="app-title">Soy el header de esta app <menu> </menu> </header> <main> <section>

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ratione, magni! Animi, molestiae minus. Ad explicabo magnam sit corporis, accusantium voluptatem sed quae odit laboriosam vel delectus commodi sequi exercitationem natus?

</section> <section>

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ratione, magni! Animi, molestiae minus. Ad explicabo magnam sit corporis, accusantium voluptatem sed quae odit laboriosam vel delectus commodi sequi exercitationem natus?

</section> </main> <script src="app.js"></script> </body> </html> ```
estaba probando el codigo del profe y cuando intento verlo en el navegador me muestra de la siguiente forma en vez de mostrarme el elemento... alguien sabe porque? ![](https://static.platzi.com/media/user_upload/image-fcf2a19c-4eda-4474-bc35-2ab63e054bff.jpg)
Para acceder al segundo hijo de un elemento que tiene cuatro hijos, puedes utilizar la propiedad `children` y acceder al índice correspondiente. Recuerda que los índices en JavaScript comienzan desde 0. Por lo tanto, el hijo número 2 se accede con el índice 1: ```javascript const parent = document.getElementById('tuElementoID'); // Reemplaza 'tuElementoID' con el ID del elemento padre const secondChild = parent.children[1]; // Accediendo al segundo hijo console.log(secondChild); ``` Este código te permitirá seleccionar y manipular el segundo hijo de un elemento que tiene cuatro hijos. Practica esto en tu proyecto para familiarizarte con el manejo del DOM.
LISTA DE METODOS PARA NAVEGAR EL DOM: // children; // live HTMLCollection // childNodes; // live NodeList // firstChild; // live NodeList // firstElementChild; // non-live HTMLCollection // lastChild; // live NodeList // lastElementChild; // non-live HTMLCollection // previousSibling; // live NodeList // previousElementSibling; // non-live HTMLCollection // nextSibling; // live NodeList // nextElementSibling; // non-live HTMLCollection
Les comparto el codigo de la clase//LLEGAR A ELEMENTOS HIJOS //1-PADRE const parent = document.getElementById("parent"); console.log("PADRE") console.log(parent); //2-HIJOS const children = parent.children; console.log("HIJOS") console.log(children); //3- SOLO EL PRIMER HIJO const firstChild = parent.firstElementChild; console.log("PRIMER HIJO") console.log(firstChild); //4- ULTIMO HIJO const lastChild = parent.lastElementChild; console.log("ULTIMO HIJO") console.log(lastChild); //5- UN ELEMENTO ANTES const previousSibling = parent.previousElementSibling; console.log("ELEMENTO ANTERIOR") console.log(previousSibling); //6- SIGUIENTE ELEMENTO (NO HIJO) const nextSibling = parent.nextElementSibling; console.log("SIGUIENTE ELEMENTO (NO HIJO)") console.log(nextSibling); // children; // live HTMLCollection // childNodes; // live NodeList // firstChild; // live NodeList // firstElementChild; // non-live HTMLCollection // lastChild; // live NodeList // lastElementChild; // non-live HTMLCollection // previousSibling; // live NodeList // previousElementSibling; // non-live HTMLCollection // nextSibling; // live NodeList // nextElementSibling; // non-live HTMLCollection //7- SELECCIONAR PRIMER LI const children2 = document.querySelector("li"); console.log("PRIMER LI") console.log(children2); //8- SELECCIONAR PADRE DE LA POSICION DONDE ESTOY (li) const parent2 = children2.parentNode; console.log("PADRE") console.log(parent2); //8- SELECCIONAR ELEMENTO PADRE const grandParent = children2.parentElement; console.log("PADRE") console.log(grandParent); //9- ELEMENTO MAS CERCANO QUE SE PARESCA O SEA MENU const grandGrandParent = children2.closest("menu"); // este último es el más utilizado console.log("ELEMENTO MAS CERCADO QUE SE PARESCA O SEA MENU") console.log(grandGrandParent); // parentNode; // live NodeList // parentElement; // non-live HTMLCollection // closest(selector); // este último es el más utilizado ```js //LLEGAR A ELEMENTOS HIJOS //1-PADRE const parent = document.getElementById("parent"); console.log("PADRE") console.log(parent); //2-HIJOS const children = parent.children; console.log("HIJOS") console.log(children); //3- SOLO EL PRIMER HIJO const firstChild = parent.firstElementChild; console.log("PRIMER HIJO") console.log(firstChild); //4- ULTIMO HIJO const lastChild = parent.lastElementChild; console.log("ULTIMO HIJO") console.log(lastChild); //5- UN ELEMENTO ANTES const previousSibling = parent.previousElementSibling; console.log("ELEMENTO ANTERIOR") console.log(previousSibling); //6- SIGUIENTE ELEMENTO (NO HIJO) const nextSibling = parent.nextElementSibling; console.log("SIGUIENTE ELEMENTO (NO HIJO)") console.log(nextSibling); // children; // live HTMLCollection // childNodes; // live NodeList // firstChild; // live NodeList // firstElementChild; // non-live HTMLCollection // lastChild; // live NodeList // lastElementChild; // non-live HTMLCollection // previousSibling; // live NodeList // previousElementSibling; // non-live HTMLCollection // nextSibling; // live NodeList // nextElementSibling; // non-live HTMLCollection //7- SELECCIONAR PRIMER LI const children2 = document.querySelector("li"); console.log("PRIMER LI") console.log(children2); //8- SELECCIONAR PADRE DE LA POSICION DONDE ESTOY (li) const parent2 = children2.parentNode; console.log("PADRE") console.log(parent2); //8- SELECCIONAR ELEMENTO PADRE const grandParent = children2.parentElement; console.log("PADRE") console.log(grandParent); //9- ELEMENTO MAS CERCANO QUE SE PARESCA O SEA MENU const grandGrandParent = children2.closest("menu"); // este último es el más utilizado console.log("ELEMENTO MAS CERCADO QUE SE PARESCA O SEA MENU") console.log(grandGrandParent); // parentNode; // live NodeList // parentElement; // non-live HTMLCollection // closest(selector); // este último es el más utilizado ```
¿Cómo puedo comentar en VSC varias líneas de código a la vez? Como se hace en el minuto 12:30 en el video.
**Para quienes se quedaron con las ganas de saber como acceder al segundo hijo.** Seria algo cómo esto: document.getElementById("parent").children\[1]; //\[1] dado que en cualquier array el segundo elemento está en la posición \[1] <u>Senshito papá :D</u>
hola, no me funciona mi codigo, no entiendo porque el child de article es undefine, ya intente con diferentes metodos, byClass,ById ByTagName. no hubo cambio. este es mi codigo```js <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Dom manipulation notes</title> <script> const papaito= document.getElementsByClassName("article"); console.log(papaito) console.log("estos son los hijos",papaito.children) </script> </head> <body> <main>

Consulting DOM elements

There are 2 main categories of methods to make requests to the Document

  • getElementby_("idNameOrWherever"): Id, ClassName, TagName...
  • querySelector_(".selectorOrselector"):All

The first one gives us an HtmlColection where the changes applied are seen in real time and is better for performance The second one gives us a node list whe the changes can't be seen in real time.

Surfing the DOM with code.

<article class="article">

For this is usefull to think about the DOM as a family tree, then to fix on an element that we can call parent, an then acces to the atributes: <menu>

  • .children
  • .firstElementChild
  • .PreviusElementSibiling
  • and much more following the same pattern more or less </menu>

    You can also use the query method that we talk about earlier to fix a child and move from it using the next

  • .parent
  • .closest("grandparent")
  • </article> </main> </body> </html> ```
    Traer el segundo hijo: ``` //traer los hijosconst children = parent.childrenconsole.log(children) //primer hijolet firstChild = parent.firstElementChildconsole.log(firstChild) const lastChild = parent.lastElementChild;console.log(lastChild); //segundo hijoconsole.log(children\[1]); ```
    De los métodos vistos en clase sobre la navegación desde hijos a elementos padres o hermanos hay otro que es: parentNode -> Devuelve el nodo padre del elemento actual ej. element.parentNode
    hola, me encontre este comportamiento muy curioso del codigo y quisiera que alguien me explicara el porque o si mi hipotesis es valida. Hipotesis: como tengo la etiqueta script dentro del head, y el codigo js dentro de ella directamente,(no en un archivo aparte) al correr el js aun no existe ningun id parent.por eso la variable queda null. codigo: ```js const papaito= document.getElementById("parent") console.log(papaito) const children =papaito.children ``` Comportamiento observado: si corro ese mismo codigo dentro de la consola del inspector la variable papaito no queda en null, trae el elemento de id parent, que tambien es un menu, pero si es en la etiqueta script dentro del head la variable papaito queda en null
    Una manera de explicar muy buena!
    k