I ran into a reaction I couldn’t explain today while working with some very basic Jquery today and I was hoping one of you could explain to me what is occurring to lead to these results
So I have a DOM model (simplified here)
<div class="ObjectContainer">
<div class="Object">
<div>stuff</div>
<div class="Object">
<div>stuff</div>
The idea was to set an attribute on the last Object using this code:
$('div.ObjectContainer').find('div.Object :last').attr("index", "1");
I understand now the code here was incorrect and the proper find selector should be ‘div.Object:last’, but it is the results I don’t understand. When I executed the first code this occurred:
<div class="ObjectContainer">
<div class="Object">
<div index="1">stuff</div>
<div class="Object">
<div>stuff</div>
Could someone explain to me how my initial selector managed to set an attribute on a child node?
Spaces indicate matching against descendants. For every space, you’re descending (at least) one level and applying your selector to the children of the previously selected elements.
For example:
Will match a
<div>with thecontainerandpostclasses, while the following:…will match any element with the class
postwhich descend from a<div>with a class ofcontainer.This will match
<div class="container"><p class="post"></p></div>, but it will also match any.post, no matter how deeply nested it is:You can think of it as matching in stages: First elements matching
div.containerare found, and then each of those elements (and all of their sub elements) are searched matches against.post.In your case,
div.Object :lastfirst finds all<div>tags with theObjectclass, and then searches within each of those for elements matching:last, that is any element which is the last element in its container. This applies to both<div index="1">stuff</div>and<div>stuff</div>.Spaces work exactly the same way as chaining multiple calls to
find, so if you understand how that works, you can understand how spaces affect a selector. These are identical: