FREELessons: 29Length: 8 hours

Next lesson playing in 5 seconds

  • Overview
  • Transcript

2.3 The Basics of Querying the DOM

Welcome back to Learning jQuery, day three. I'm your host, Jeffrey Way. And in today's lesson, I'm gonna teach you the basics of querying the DOM. You've already learned how to use a CSS selector if we want to grab this unordered list with a class of emphasis. In the same way that we can do it in CSS, by doing ul.emphasis, or leaving the tag name off entirely. We can do the same thing in jQuery. jQuery, ul.emphasis. And now, that will query the dom and will return this section right here wrapped within the jQuery object. Now, let's take a look at some different ways that we can continue on from that point. I'll give myself a little extra space. And now, once again, let's say we want to grab that first list item. Well at this point, we already have a selector. So how can we go from there, and continue our search? We can't do anything like this, where we continue on. That's not going to work. We wanna use specific methods that are available to the jQuery object. The first one we're going to take a look at is children. .children and we're going to look for list items. Now, the way children works is it's going to look for immediate children of a parent. If you're not familiar with the idea of ancestors and descendants, I'll give you an example. These list items right here, are children. They're direct children of their parent, which is the UL. However, what if right within here, we had a nested hello from the nest. This is not a direct child of this unordered list. It is what we call a descendant. This list item is a direct child of this unordered list. And this unordered list is a direct child of the list item. So right here what we're saying is get the direct children of the UL with a class of emphasis. If you're more familiar in CSS, it's the same thing as essentially doing ul.emphasis li. And again the difference between that and doing ul.emphasis li as in the first example, we're looking for any list item as long as it is a descendant of the UL. So it's going to select this one, this one, this one, and that one. However, in the second example, we're saying nope limit it to your children only. Don't worry about grandchildren or anything else like that. Just children. So the second selector is only going to apply to this one and to this one. And if you want some proof, let's make the color red. Let's comment out our jQuery for the moment. You'll find that yes, all of them are red, but only because of the way CSS works. This child list item is inheriting its color. So, if we were to set a base styling, for example, list items, color, black. Set a base style and then we're going to override only the direct children of the unordered list. Now, you'll see the actual difference. These two are being selected. This one is not. And the same thing is going to be true for jQuery. So, I'll remove those. I'll come back and uncomment my jQuery and we'll embed CSS for now. The color is green. Let's see if it works. Reload the page and sure enough we've only selected the very first two list items and adjusted their styling. Now what if that's not what you want? You genuinely want to select all list items as long as they're contained within the UL. Well in that case, rather than children, you're going to use the find method. And the only difference is it's going to continue searching even beyond the direct children. To come back, reload the page and now you'll see that all three of those have been selected. So the basic rule of thumb is, if you only ever need the direct children, stick with the children method. That will be somewhat faster because jQuery doesn't have to continue searching beyond that point. However, if you're unsure, the performance difference is going to be pretty much impossible to detect. So you can stick with find. Now, we've learned about children, find, what if want to move around one at a time. For example we found all list items, let's adjust that and we only want to grab the first list item. And this time rather than adding the CSS we're going to add a class of emphasis once again. Come back. Let's add that class in, like so. And now when I come back down, I've already taught you that we could do it with CSS. First child, or you could do nth-child 1. This is all CSS, we can do this with simple CSS and CSS3. However if you want to stick with jQuery, and the advantage to that is, it will work in Internet Explorer 6 as well. So if you require old browser support, sometimes it's better to use these complicated selectors in your Java Script writer, rather than CSS. So we have a couple options. I'm gonna switch this back to children, and we're going to select the very first one. And this is what you can call a custom selector that jQuery provides, :first. Reload the page and we are selecting the first one. Now it's important to note that these are custom in that they're not provided in CSS. They're helpers that jQuery provides. Most of the time though, if there is a CSS alternative, you will always want to use that one. That we way we can take advantage of the processor's native CSS parsers and it'll work a little bit more quickly. Now, we have other options. We can also use the first method. ul.emphasis, get the direct children, and then I want you to filter that down. I only want to select the first one. So, if we do this one at a time. We get the UL with a class of emphasis. Then we get the direct children. Which will be these two right here. And then we're saying, nope, I only want the first one of that set. So now we've brought it down to here and we're going to add the class of emphasis. Reload the page and once again we've made that selection. Now what if you want to select the second one? Well once again with CSS we could do nth-child 2 and let's try that. And this time we're going to rather than adding a class, I'm going to set the text, and that's our way of saying take the value out and we're going to specify what the value is. And I'll add, added with jQuery and I'll add the closing parenthesis. All right, let's try it out. Reload and we get added with jQuery. Now, if we want to use other methods, let's bring that back to li and we could say, eq. This is the eq method. We pass an integer to it. So if I hit 1, if we reload the page, you'll see that that selects the second item, and that might be a little confusing. Why is one selecting the second item? Let's try doing number 2. Now we're selecting the third item, and this is an important concept to understand many things in JavaScript are zero based, which means the very first item is zero. So I do eq 0, what we're really saying is 1. Get the two list items and filter that down. We only want eq 0, or the first item. And then set its text. And now if I reload, we're adjusting that one. So an easy way to think about it is figure out the number you wanna grab. So if we add a couple more here. Three and four. Let's say we want to style this fourth one. You would do 4 minus 1 to compensate for the fact that it's zero based. So if we wanna target this one right here we will do 4 minus 1 is 3. And that's what we will pass to the EQ method. Reload. And there we go one, two, three, four. But sometimes you need to move back and forth. For example, maybe I'm already at this fourth one and I need to maybe go to its previous sibling or its next sibling. So let's add one more here. Item five. And we know at this point we have successfully selected this list item. But what if from that point I want to move on to the one that follows it? Well, I could say, eq.(3), and now I'm going to go to the next one. And I want you to pay attention, this is what we call chaining and this is something that jQuery does very, very well. It allows us to stack methods upon each other. And the way it's working behind the scenes is that. Every method call will return the jQuery object. In that way, you can just continue on as long as you want, but be smart about it. Don't make it too complicated to understand. Let's try this again. Reload. And now we've selected the fifth item. So, already I hope you're realizing that jQuery's very natural to work with. If you wanna grab the first list item, you use first. If you wanna go tot he next list item, you use next. If you wanna go to the previous list site and in our case you can do p r e v for previous, reload and now we're styling that one. If you wanna select direct children, you use children. If you wanna select descendents, you use find. These are all very natural. And when you're doing these at first, try to phrase it out. I want the ul with the class of emphasis. Then it's children, then we're going to get the fourth list item and go to the previous one. Now in this case of course, you would never do this like so, because you can always select that manually. For example, ul.emphasis li:nth-child(3). Reload. And now, we've updated that. But the idea is that sometimes, you don't always have the luxury of specifying your entire selector. Sometimes, you need to figure out this stuff out dynamically, which is where these DOM traversal methods come into play. Now before we move on to the next one, remember that you don't have to make these in to huge lines. You can separate them like so. And it's fairly common to use indentations to provide feedback of where you are in the chain. So for example, we've selected the UL, now we're going to get eq 3, which is the fourth list item. And then we're going to get the previous one. And we'll set it's text to added with jQuery. So you can style this how you want to make it most readable for you. It's still going to work the exact same way. So I will comment this out and now we're going to take a look at using parent and parents. Now it'll work essentially the way you think as long as you think of the DOM as a family tree. You have your children, you have your descendants. You have your parent, and you have your grandparents. The same concept will work when querying the DOM. This time, let's get the list items. And from that point, I would move up and select this unordered list. And to do that, we use parents. Get the parent of the list items. Now in this case, we have a list of emphasis. And that will make the color of the list items green. Like so. Let's remove that, so list item, get the parent, and now to remove a class. We've already discussed add class. We can also use remove class, and we'll remove that class of emphasis. Now if I save that and reload, the class has been removed. To verify that, I will open crumb developer tools, container, and you'll see that the emphasis class has, in fact, been removed. Excellent. So I could also say, parent ul to be a little more specific. Reload and we're going to get the same effect. But watch what happens. You might be thinking, well, let's go up to container. Let's instead apply the class to the container element itself. There we go. Now all the text is green. From the point of the list item, we want to filter up to the container and remove that class. So li, parent, container, removeClass, container. Let's see what happens there. Reload. Nope, that's not working. Let's check Chrome developer tools. Nope, there's no error. So what is the deal here? And just as children is for working with direct children, parent refers to your direct parent. Watch what happens if I change this to parents. Reload the page. Now its working because we are now saying move up the DOM tree and find an element with a class of container. And if you'd like to be a little more specific its slightly better for a performance, you can specify a element name. Now again, whether you use parent or parents will depend on how well you know the DOM. Now we also have another method called closest. Like so, if I reload the page, we get the exact same effect. But how does this one work? What is the difference? Well this time rather than me explaining it to you, I want you to also get in the habit of visiting Let's do that now. Now this is a website that you'll absolutely want to bookmark. In addition to referencing the jQuery source, which admittedly can be a little overwhelming at first, this site will be an excellent way to learn what methods are available. For example, we can see add class. We've already taken a look at this one. Adds a class to each set of matched elements. In our case, we're going to research closest, right here. And you'll see, it will get the first element that matches the selector and it begins at the current element. Okay, so right here, begin at the list items and then progress up through the DOM tree. But now still you might be thinking, well that seems like the exact same thing as parents. Now once again, you could research the parents method and see what the difference is, but this time I will explain it to you. It's a very settled difference between the two, but it's important to understand. So this time, we're going to use the console. And I'm gonna console.log, and this time just for the example, I'm gonna add one more div with the class of container, like so. So now from the point of the ul, there's one, and two parents that both have a class of container. Let's try this out, ul.parents and we're going to look for the element with a class of container. And then I'm gonna copy this and this time I will do closest. Okay, let's try this out. I'm gonna reload the page and you'll see the difference here. So the first one that we've logged represents the parents method. The second one will represent the closest method. So the way the closest method will work is it's going to return the very first element if finds that matches this selector. So from the ul it's going to look up as soon as it finds a parent that has a class of container it returns, which is what we've done right here. But parents will filter up and it'll go yep there's one let's keep going up. Parents will filter all the way up the DOM tree and then it finds another. So it will return two of them. Another distinction worth making is what if the class we're looking for is on the current element? So now we're saying get the ul and then find the closest element that has a class of container. But the closest element is the element itself. So let's try once again. Reload, and now take a look. Parents will first get that element, but then it just starts going up the tree, and it will go all the way up saving anything that matches that selector as it goes. Now the closest will go wait a minute. This element itself has a class of container. I'm gonna return that, and I'm done. I'm not doing anything else. And that's why many times if you're only looking for a specific element you'll want to stick with the closest method rather than the parent. And that will do it for today. So your assignment for tonight is play around with these methods. Figure out how you can move around the DOM. Find list items, move up to their parent. Move to the element that comes after. Try to drill this into your brain so that you don't have to remember. How would I search for this? It's ingrained in your memory. And then, when you're ready for that, you're ready to move on to lesson four.

Back to the top