They… are but they aren’t reciprocal. It’s all about tree traversal and scope.
In our previous example, we identified that $(this) is pointing at an element.
Consider what you want to do now, in English. Not even going to talk code yet.
“What I want to do is add an element to this group, but only if there aren’t already 10 of them in the group that I’ve clicked the button on.”
Well, we covered part of this before. We know how to add an element to the group. We had that answer in post 11. What about the rest of it?
So, we clearly need an if. I mean, we said the word if in our sentence, so clearly we need one. But an if needs a condition.
Our condition requires us to count things, because we know we shouldn’t do anything if there’s already 10 of these elements. But how do we know how many elements are in the group? In fact, how do we know which ‘group’ we’re talking about at all?
The group I’ve clicked the button on. Ah, so here’s our triggering element - the point at which we enter the DOM tree. We enter, pointing at the button that was clicked.
Now, I’ve given you one method of finding the answer to the green piece. There is another (probably simpler, but it’s good to learn about traversing anyway… think of it like maths classes in school. You learn the complex way, and then you learn the shortcuts )
.parent goes ‘up’ one level of the DOM tree. So in the case of your code, .parent() shifts the pointer up one level, and points it at the ‘class’
<div>. Note that we can keep going up and up and up until we hit the document (the root of the tree) by invoking parent multiple times;
var mystery = $(this).parent().parent().parent();
(Pop quiz: What element is
mystery pointing at, if
$(this) is pointed at Semester 2’s button?)
.find(selector) is almost the reciprocal of that function, but it searches the children of the target element for matches to
selector. This way you can identify how many
<div>'s are inside of an element, without having to count the number of buttons too.
.children(selector) is almost the same as
.find(selector), except it only searches the immediate children of the target, and find recursively digs into the children. In this particular example, it makes no difference which you use, because the children of your semester don’t themselves have children.
The line that adds a class was correct in post #11. Leave that alone, it goes inside our if. Write for me the if condition that satisfies the green text above.