02. Retrieving a single element and DOM traversal

When selecting elements from the DOM, we can either select one or many nodes. Let's start with retrieving a single element.

To retrieve an element, we use DOM queries. These are the methods used through JavaScript that we can use to find elements on the DOM tree. Oftentimes, the elements we select are stored into a variable, which serves as a reference to the node; this is known as caching.

getElementById

The most efficient way to obtain an element is through its id attribute. We may do this with the getElementById() method, in which we simply pass in the name of the id. Since we know that no two elements can share the same id, we are ensured that the browser terminates right after finding the first id, resulting in quickness and responsivity.

var firstItem = document.getElementById('first')

This command will store the reference to the element with an id of first within the firstItemvariable.

querySelector

Another way to select just one element is through a query selector. Given a CSS selector, this returns only the first matched item.

firstParagraph = document.querySelector('p') # First 

tag. document.querySelector('.item') # First element with a class "item"

Traversing the DOM - single elements

Once we have selected a single element, we may access the nodes around it through these properties:

parent
Select parent of current node.
previousSibling
Select the previous sibling node.
nextSibling
Select the next sibling node.
firstChild
Select the first child of current element.
lastChild
Select last child of current element.

Build modern and responsive webpages

HTML & CSS

Build modern and responsive webpages Try Front-end

This book teaches HTML as if it's for anyone - hobbyists, students, and professionals - and it's full-color throughout. It utilizes information graphics and lifestyle photography to explain the topics in a simple way that is engaging. You can progress through the chapters from beginning to end or just dip into topics of particular interest at your leisure.

$ Check price
29.9929.99Amazon 4.5 logo(926+ reviews)

More Front-end resources

Aching back from coding all day?

Inversion Therapy Table

Aching back from coding all day? Try Back Problems

Stretch out your back and relieve your back muscles with inversion therapy. This device counteracts the forces of gravity on the body by decompressing and elongating the spine. By using this product just ten minutes a day, you can be well on your way to improved circulation and posture while relieving muscle aches, back pain and stress.

$$ Check price
119.98119.98Amazon 4.5 logo(1,700+ reviews)

More Back Problems resources

Ad