What does a space in a jquery selector mean?

2019-01-14 11:49发布

问题:

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?

回答1:

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:

div.container.post

Will match a <div> with the container and post classes, while the following:

div.container .post

...will match any element with the class post which descend from a <div> with a class of container.

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:

<div class="container">
  <div>
    <div>
      <a class="post"> <!-- matched -->
    </div>
  </div>
</div>

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 the Object 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:

$('div#post ul.tags li');
$('div#post').find('ul.tags').find('li');


回答2:

$('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')



回答3:

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

$('.ObjectContainer .Object:first')

So the space in jQuery selector separates the parent node and it's children