JavaScript DOM Elements
Finding the right elements is the first step of almost every DOM task, and the browser gives you several precise ways to do it.
Why finding elements matters
Before you can change text, styles, or attributes, you first have to get a reference to the element you want to work with. Choosing the right finder method keeps your code short and reliable. The best choice depends on whether you are targeting one unique element or a group of related elements.
Finding a single element by id
When an element has a unique id, getElementById is the clearest and fastest way to reach it. It returns the element directly, or null if nothing matches, so you can check the result before using it.
Selecting one element by id
<!DOCTYPE html>
<html>
<body>
<p id="output"></p>
<script>
const output = document.getElementById("output");
if (output) {
output.textContent = "Element found and ready.";
} else {
console.warn("No element with id 'output' exists.");
}
</script>
</body>
</html>Finding elements with CSS selectors
querySelector and querySelectorAll accept any valid CSS selector, which makes them the most versatile finders. Use querySelector when you only need the first match, and querySelectorAll when you need to work with every match as a list.
Selecting by class, tag, and combinations
<!DOCTYPE html>
<html>
<body>
<nav>
<a href="/home">Home</a>
<a href="/about">About</a>
</nav>
<div class="card">Card content</div>
<script>
// First element with class 'card'
const card = document.querySelector(".card");
// Every anchor inside the navigation bar
const navLinks = document.querySelectorAll("nav a");
// Loop over the matches
navLinks.forEach((link) => {
link.setAttribute("target", "_blank");
});
</script>
</body>
</html>Choosing the right method
Moving between related elements
Once you have one element, you can navigate the tree to reach nearby elements without another lookup. Properties such as parentElement, children, firstElementChild, and nextElementSibling let you move up, down, and across the branches.
- parentElement moves up to the element that contains the current one
- children lists the element nodes directly inside the current element
- firstElementChild and lastElementChild reach the ends of that list
- nextElementSibling and previousElementSibling move across siblings