Check out a free preview of the full Advanced JS Fundamentals to jQuery & Pure DOM Scripting course:
The "Finding from the Document" Lesson is part of the full, Advanced JS Fundamentals to jQuery & Pure DOM Scripting course featured in this preview video. Here's what you'd learn in this lesson:

JavaScript provides an extensive API for finding elements in the DOM using the Document object. This API includes methods like getElementByID() and querySelector(). Justin gives a few code examples using these APIs.

Get Unlimited Access Now

Transcript from the "Finding from the Document" Lesson

>> [MUSIC]

>> Justin Meyer: We're gonna fill out some set of these, depending on how quickly we move. Some of them, I just might implement for you guys, or show you how to do it. But this is a big nice set of jQuery's functionality. And we're gonna use that to explore the DOM.

[00:00:23] And the first thing we're gonna talk about is just how do you find elements in the DOM. So modern browsers provide a nice set of methods that given a document, which is really, this document represents the HTML structure of the page. Given that, you can find an element by id, by class name, by tag name, by a CSS selector, by a lot of different methods.

[00:00:50] So just to give a quick example of what these do, if you've never seen them before, document.getElementById finds an element that has an id attribute, that matches what's passed in here, and will return that single element. getElementsByTagName, one thing I should also reference, I'm going in order of performance.

[00:01:13] getElementById is the fastest way to retrieve an element in the whole document. getElementsByTagName is a way to get all elements that match a particular tag. So, if I wanted all li's in my page, this would get me all the li's. And the cool thing about this fun fact is this is a live array.

[00:01:40] Like it's not actually an array, it's a node list. But it changes, if I insert an li, whatever this object, the node list that this thing is returning, will dynamically change as li's are added or removed to the page, which is crazy. I've never had to use that functionality for some kind of benefit but that does work.

[00:02:05] Another fairly fast selector is getElementsByClassName. This will get all elements, you see this has this class attribute, it has at least one part matching. So, if I had contact space important, in quotes, this would still match this element.
>> Justin Meyer: querySelectorAll gets all elements that match a CSS selector.

[00:02:33] Hopefully everybody here is, at least, familiar with CSS selectors. If not, like ping me or Alexis, right after and we'll explain it to you. But this will get all elements that match a CSS selector.