how to add a class to parent child of a div

问题内容:

<div class="parent">
 <div class="child-class"><div>
 <div class="child-class"><div>
 <div class="child-class"><div>
</div>

Hi there, I need to add a class to second child-class using jQuery

somebody please help me

问题评论:

    
um so select it with .eq(1) ??
    
There are two parts: (1) locate the second child element within the parent div, then (2) add a class to the found element. What part of that do you not know how to do? You can easily find information for each of these operations doing a few seconds of Google searching if you’re not sure.

答案:

答案1:

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).

答案评论:

答案2:

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.

答案评论:

答案3:

The following code will add class named “new_class” in the second child div:

$('.parent > .child-class:nth-child(2)').addClass('new_class');

答案评论:

答案4:

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.

答案评论:

原文地址:

https://stackoverflow.com/questions/47754681/how-to-add-a-class-to-parent-child-of-a-div

添加评论

友情链接:蝴蝶教程