What does a space in a jquery selector mean?

前端 未结 3 682
一生所求
一生所求 2020-12-05 10:14

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

相关标签:
3条回答
  • 2020-12-05 10:57

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

    0 讨论(0)
  • 2020-12-05 11:00

    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');
    
    0 讨论(0)
  • 2020-12-05 11:02

    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

    0 讨论(0)
提交回复
热议问题