Traversing means "move through", are used to "find" (or select) HTML elements based on their relation to other elements. Start with one selection and move through that selection until you reach the elements you desire.
By using
Closest
const closestElement = targetElement.closest(selector);
Siblings
const previous = element.previousSibling;
const next = element.nextSibling;
Children
const container = document.querySelector('#container');
const children = container.childNodes;
Parent
const current = document.querySelector('#main');
const parent = current.parentNode;
1.getElementById()
<div id="user">Get Element by ID</div>
const userId = document.getElementById(user)
console.log(userId)
/* Output
<div id="user">Get Element by ID</div>*/
<!-------->
2.getElementsByClassName()
<div class="user">Get Element by Class Name (1)</div>
const userClass = document.getElementsByClassName('user')
The getElementsByClassName() returns an array-like object of the elements.
We can convert the array-like object to an actual JavaScript array with the Array.from()
method or the spread operator.
/* With the Spread Operator */
const userClass = [...document.getElementsByClassName('user')]