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 >
<div ></div>
<div ></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');
CodePudding user response:
addClass
takes the className i.e.new-class
not.new-class
iteration-odd
is className notiteration-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 >
<div ></div>
<div ></div>
</div>
CodePudding user response:
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 >
<div >1</div>
<div >2</div>
</div>
CodePudding user response:
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 >
<div >1</div>
<div >2</div>
</div>
CodePudding user response:
$('.iteration-odd div:nth-child(2)').addClass('new-class');