skip to Main Content

How to query div with jquery of class ac but inside a not ab ?

If i query $('.a .ac') it finds ac but inside ab

<div class="a">
  <div class="ab">
     <div> class="ac"></div>
  </div>
  <div> class="ac"></div>
</div>

2

Answers


  1. You can use a child-combinator >:

    The child combinator (>) is placed between two CSS selectors. It
    matches only those elements matched by the second selector that are
    the direct children of elements matched by the first.

    console.log($('.a > .ac'))
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div class="a">
      <div class="ab">
         <div class="ac"></div>
      </div>
      <div class="ac"></div>
    </div>
    Login or Signup to reply.
  2. You can select an immediate child element with the child combinator, for example:

    $('.a > .ac').css('color', 'red');
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div class="a">
      <div class="ab">
         <div class="ac">inside ab</div>
      </div>
      <div class="ac">not inside ab</div>
    </div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search