How do we get individual and multiple elements from the DOM?

If an element has the id attribute, we can get the element using the method document.getElementById(id), no matter where it is.

So we see our home link has an id of home:

const el = document.getElementById("home");
console.log(el);

Note that we should only have elements that include unique id values. If we want to have multiple elements share the same style, use a class

What if we want to get multiple elements, like multiple links? We can use querySelectorAll. It returns to us the elements that match a given selector. For example, to get all the links, we could just say:

const links = document.querySelectorAll("a");
console.log(links);

And it returns to us a NodeList, which we can iterate over with .forEach

What about a single link? We can use querySelector:

const link = document.querySelector("a");

The call to elem.querySelector(css) returns the first element for the given CSS selector.

In other words, the result is the same as elem.querySelectorAll(css)[0], but the latter is looking for all elements and picking one, while elem.querySelector just looks for one. So it’s faster and also shorter to write.

Now what if we want to find the link that matches a given url? Say the link that points to the login route?

Let's iterate over links:

links.forEach((link) => {
  link;
});

And we can see if one of these links satisfies such a condition with the matches method:

links.forEach((link) => {
  if (link.matches('a[href="/login"]')) {
    const loginLink = link;
    console.log(loginLink);
  }
});

And also in addition to querySelector and querySelectorAll, there are some alternatives, like: let getElementsByTagName. For example if we wanted to get all the divs:

divs = document.getElementsByTagName("div");

Note that it should include an s (plural). And this also returns an html collection, like querySelectorAll. Note that there are some difference between getElementsByTagName and querySelectorAll. First of all, querySelector All can include any CSS selector, whereas getElements can only accept selectors that are tags (like div or a)

And also getElementsByTagName is a live collection, whereas querySelectorAll is static. So if new elements are added, getElementsByTagName (or other variants of it like getElementsByClassName), will pick up the new elements that are added to the DOM while querySelectorAll won't

Most of the time, though, querySelector and querySelectorAll are what we will use because they have the most powerful ability to search for single or multiple elements by providing whatever valid CSS selector we like.