<div class="parent"> <div class="child-class"> <div> <div class="child-class"> <div> <div class="child-class"> <div> </div>
I need to add a class to second child-class
using jQuery
Adress the second child of the parent via CSS Selector:
$('.parent > .child-class:nth-of-type(2)').addClass('your-class');
Advantage over using nth-of-type
instead of nth-child
is beeing more precise in selecting what you want. The nth-child
will select any child of your parent. nth-of-type
will only select children with a certain type (in this case class child-class
).
You can use :nth-child
selector at this context,
var elem = $(".parent > .child-class:nth-child(2)");
Note that, the index that is being passed into the selector would start from 1 not from 0.
Here you go with a solution
$('.parent > .child-class:eq(1)').addClass('newClass');
.child-class { width: 100px; height: 50px; border: 1px solid; } .newClass { background: red; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="parent"> <div class="child-class"></div> <div class="child-class"></div> <div class="child-class"></div> </div>
I've used jQuery eq
selector.
Documentation: https://api.jquery.com/eq-selector/
Hope this will help you.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.