This course is out of date and does not reflect Frontend Masters current standards. We now recommend you take the JavaScript: The Hard Parts course.
Transcript from the "Finding from the Document" Lesson
[00:00:00]
>> [MUSIC]
[00:00:03]
>> 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.