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?
$('div.ObjectContainer').find('div.Object :last')
results in a wild card effect. it looks for any child with the psudo class of :last. Thus it simply picked div:last. It's equivalent to$('div.ObjectContainer').find('div.Object div:last')
Using jQuery, you can find any DOM obj by providing it's ID, class name, tag type, etc or just find the parent first then specify the nested child you want
For example, you can find the first Div. Object by this query
So the space in jQuery selector separates the parent node and it's children
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 thecontainer
andpost
classes, while the following:...will match any element with the class
post
which 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.container
are found, and then each of those elements (and all of their sub elements) are searched matches against.post
.In your case,
div.Object :last
first finds all<div>
tags with theObject
class, 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: