skip to Main Content

I’m triying to add a class to a child but only on children containing a specific class

This is an example of the existing HTML:

    <div class="iteration-Odd">
     <div class="style1"></div>
     <div class="style2"></div>
    </div>

And I need to add an additional class to the div with "style2"

Tried this with no luck:

$('.iteration-Odd').find('.style2').addClass('.new-class');

4

Answers


  1. Please check this,

    you need to replace O to o

    $('.iteration-odd').find('.style2').addClass('new-class');
    .new-class{
      color:green;
      background-color:red;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div class="iteration-odd">
         <div class="style1">1</div>
         <div class="style2">2</div>
        </div>
    Login or Signup to reply.
  2. addClass takes the className i.e. new-class not .new-class
    iteration-odd is className not iteration-Odd

    $('.iteration-odd').find('.style2').addClass('new-class');
    div {
      height: 1rem;
      background: wheat;
      margin: 10px 0;
    }
    
    .new-class {
      background: yellow;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div class="iteration-odd">
      <div class="style1"></div>
      <div class="style2"></div>
    </div>
    Login or Signup to reply.
  3. Another way you can do with Parent Child jquery selector like .iteration-odd > .style2 here you don’t need to use find method

    For More detail check this link -> Click Me

    $('.iteration-odd > .style2').addClass('new-class');
    .new-class{
      color:white;
      background:red;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
     <div class="iteration-odd">
       <div class="style1">1</div>
       <div class="style2">2</div>
      </div>
    Login or Signup to reply.
  4. $('.iteration-odd div:nth-child(2)').addClass('new-class');
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search