Lesson Description

The "Selecting Elements" Lesson is part of the full, Getting Started with JavaScript, v3 course featured in this preview video. Here's what you'd learn in this lesson:

Kyle introduces different methods to retrieve specific elements in JavaScript. He explains how getElementByID returns a single element based on its ID, while getElementsByClassName retrieves multiple elements with a specific class. He then discusses the advantages of using querySelector and querySelectorAll, which allow for more flexible CSS selector usage to obtain single or multiple elements.

Preview

Transcript from the "Selecting Elements" Lesson

[00:00:00]
>> WebDevSimplified: Now, other than just getting the whole document and the whole window, we generally want to get specific elements that are on our page, and there are different ways to do it inside of JavaScript. The first method is going to be called the get element by ID. You just type this in like this, so you can say document dot get element by ID, and we can pass it in whatever ID we want and it'll try to get an element based on the ID.

[00:00:24]
So inside my index, if I were to give my H1 here an ID of hi. There we go. Now I can come in here. I can pass in that text hi, and that'll give me that element. So if I log this out, you give that a quick save, you can see over here we grab that brand new element with that ID of hi, and this get element by ID and all these other functions we're going to be talking about, they're all available directly on the document to query it for these various different things.

[00:00:51]
The important thing to note about this get element by ID is it always returns a single element or if I try to access an ID that doesn't exist, such as bye, it returns to me null. So either gives me a value or it returns to me null. It always returns either one value or a null. Another important thing to note, not really a JavaScript concept, but more an HTML concept, is all the IDs on your page should be unique.

[00:01:13]
You should never have more than one of the same ID on your page, because otherwise your get element by ID won't know which one to actually grab since it only ever grabs one single element. Also, if you're used to writing CSS code, for example, you may know that IDs are prefixed with this pound symbol. When you're using get element by ID, don't put that pound symbol in front of them, just pass the actual ID name itself.

[00:01:35]
The next method I want to talk about is get elements by class name. This is allowing you to get multiple elements based on whatever class name is applied to them. So in our case we have three separate divs, and they all have the class of content. So if I want to get every div or every element on my page with the class of content, I can call document.get elements by class name, pass it in wherever that class name is, and it'll give me all the different elements, and it returns to them in an HTML collection, very similar to an array with some differences that we will talk about, but essentially we get a collection and array of all these different elements on our page.

[00:02:06]
Now the important thing about HTML collections is while they look a lot like an array, they're technically quite a bit different. First of all, they don't contain all those fancy methods we just talked about, for each, map, reduce, none of those exist on an HTML collection. You would generally, if you want to use those methods, first need to convert that value to an array. You can use Array.from to convert an HTML collection to an array and use all those fancy methods, or you can just use a normal for loop.

[00:02:34]
Either one is going to work just fine. Now these are ways to get multiple elements or a single element, but they're not the preferred way in the browser to do that. Instead, we have query selector and query selector all, which in my opinion are the much more recommended way of getting either a single element or multiple elements. Query selector and in turn query selector all, instead of using like an ID or a class, they use any CSS selector you want.

[00:03:00]
So if you're not familiar with CSS, this may be a little bit more confusing because we're using CSS selectors. But essentially when you call query selector, you can pass it any CSS selector you want. So to get something based on ID you would prefix it with the pound symbol because in CSS, a pound symbol is how you represent an ID. Inside of CSS to represent a class, you use a dot in front of the class, so you would put that inside your query selector.

[00:03:22]
Any CSS selector you want, you can put inside of here and you can make it as simple or as complex as you want. For example, you can get all the divs by using query selector and passing in the div selector, or you can even get some complicated selectors such as the data attribute selector. Again, if you're not familiar with CSS, some of this may look a little bit confusing, so I'd recommend brushing up on some basic CSS if you want to use this query selector method.

[00:03:45]
But the way that this works is it'll essentially return to you the very first HTML element that matches your selector. So in our case, this ID header will return to me this header, this very first div. When I do query selector on the class of content, you'll notice I have two divs that have that class. It'll always return the first one, so it'll return to this first content div and completely ignore all the rest of them.

[00:04:05]
Same thing here, query selector div. There are three different divs, but again, it'll return the first one, which is my header div portion. Now query selector all is how you essentially get multiple elements. Let's say when I wanted to select elements based on this content class, I wanted all of them, I could use query selector all. It works exactly the same. It takes CSS selectors, but instead of returning one element, it returns to me an array of all the different elements, and technically it's a node list, not an array.

[00:04:34]
So when we are working with get elements by class name that returns an HTML collection, query selector all returns a node list, and there's a few different things that are important to know about them. First of all, node lists, they work very similarly to arrays. They lack most of the array methods, but they do have a for each method, which is nice because that's the most common thing you'll use on them.

[00:04:53]
Other than that though, they don't have any of the other really nice array methods. Now, when we're dealing with HTML collections and node lists, there's something you need to understand which is live versus static collections. Essentially, whenever I do a query selector all or get elements by class name, that's going to give me all the elements on my page that match that selector or match those classes.

[00:05:13]
But the interesting thing is that my HTML collection, the thing returned by get elements by class name, is live. That means if I add a new element to my page that matches that selector, it automatically updates that array for me right away. While when I use query selector all, that returns to me a static list. So even if I add a new element to my page that matches that selector, it doesn't get added to my list.

[00:05:35]
This is actually one of the big reasons I prefer query selector all because having my arrays automatically change on their own from something that happens somewhere entirely differently is confusing and difficult to work with. Here's a quick example of that in action. Essentially we have three divs on our page right here. I'm going to be getting a live collection by using get elements by class name, and you can see the length of that is three.

[00:05:57]
Now here's some code. It doesn't really matter what it does. All this does is add a div to my page and give it the class of content. It doesn't matter if you quite understand what it does, but it's just adding that new div to my page. And now without me running any query selector or get element by class name, automatically my collection has updated its length to four because it sees that new element added to the page and automatically updates itself.

[00:06:20]
This may be beneficial for some use cases, but more often than not, this makes my code more confusing to work with. This is why I prefer to use query selector all. My code for both of these examples is exactly the same. The only difference is up here I'm using query selector all instead of get elements by class name, and you'll notice, even after I add a new div to my page, the length of that list always stays the same as three because it never automatically adds elements to the array for me, which is my preferred way to work.

[00:06:46]
So when would you want to use each one? In my opinion, I pretty much always default to using query selector or query selector all depending on if I want one or many elements, and I pretty much never use these other two methods, get element by ID or get elements by class name. You could use get element by ID though for selecting elements based on their ID if you want, because it's maybe slightly more performant.

[00:07:07]
But by that, I'm talking just nanoseconds of performance that you're not going to really notice in a real world application. So you could use either one if you want, but I just stick with these two because they are the same and I can just use them everywhere in my application. Now, like I said, you can use as advanced of CSS selectors as you want. Here's just an example of a bunch of different really advanced CSS selectors.

[00:07:26]
It doesn't really matter if you understand what they mean or not. It's just to show you that it doesn't matter what it is, if it's valid CSS, you can put it in here and it'll actually do that query for you. Now here's a quick little exercise to go through. Given the HTML that I have down in this section right here, I want you to write some JavaScript that's going to update certain things. First of all, I want you to change the header's text to say welcome instead of original header.

[00:07:50]
I want you to make all the paragraphs blue. I want you to hide the last paragraph, and I want you to add a border to the inputs with the required class. Now, in order to make this a little bit easier for you, you can use the style property on any element, so style dot whatever property, so for example, border or color to change the CSS styles, and you can use text content to change the text. So element.text content will actually update the text content itself.

[00:08:19]
So let's take a quick look at the solution here. This one's a bit of a more complex problem. If we open this up, you can see we have a lot of different query selectors to do pretty much everything. So the first thing is we're doing a document query selector and we're getting that ID of main header which matches the ID of that header that we want to update. And to change the text content we can just use the text content property directly on the element because this returns to us an element and text content is a property on the element.

[00:08:44]
We then just set that to that text welcome. Finally, to change all the paragraphs to be blue, we first need to select all of the different paragraphs. And since query selector all includes a for each method, we can use that to directly loop through all of our paragraphs, and we're using the style property to change the color, which is a CSS property. That's how you change the text color in CSS, and we're setting that just to the variable blue to update that color.

[00:09:06]
Finally, to hide the last paragraph, there's a few different ways you could do this. You could have just taken this query selector all and gotten the last element from the array, or we can use the CSS selector last child, which will get us the last child and actually hide that by just setting the display here equal to none. Finally, we can add a border to all the inputs that are required by doing a query selector all with that input, input type is the type of our element.

[00:09:30]
The required class is supposed to be on all of them. We can loop through each one of those different inputs and we can change the style of the border by setting it to a two pixel red border. You can make the color or style of the border whatever you want, but essentially you just modify the border in some particular way.

Learn Straight from the Experts Who Shape the Modern Web

  • 250+
    In-depth Courses
  • Industry Leading Experts
  • 24
    Learning Paths
  • Live Interactive Workshops
Get Unlimited Access Now