我有像
这样的HTML<div class="main">
<div class="sub"></div>
<div class="sub"></div>
<div class="sub"></div>
</div>
<div class="main">
<div class="sub"></div>
<div class="sub"></div>
<div class="sub"></div>
</div>
我想为所有具有class sub和parent main的第一个div添加一个类。即;我想要HTML
<div class="main">
<div class="sub newclass"></div>
<div class="sub"></div>
<div class="sub"></div>
</div>
<div class="main">
<div class="sub newclass"></div>
<div class="sub"></div>
<div class="sub"></div>
</div>
如何使用jquery实现此功能?
答案 0 :(得分:2)
您可以使用以下代码
►方法1
$('.main').each(function(){
$(this).find('.sub').first().addClass('newclass');
});
工作演示
$('.main').each(function(){
$(this).find('.sub').first().addClass('newclass');
});
&#13;
.newclass{
color:red
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="main">
<div class="sub">1</div>
<div class="sub">2</div>
<div class="sub">3</div>
</div>
<div class="main">
<div class="sub">1</div>
<div class="sub">2</div>
<div class="sub">3</div>
</div>
<div class="main">
<div class="sub">1</div>
<div class="sub">2</div>
<div class="sub">3</div>
</div>
<div class="main">
<div class="sub">1</div>
<div class="sub">2</div>
<div class="sub">3</div>
</div><div class="main">
<div class="sub">1</div>
<div class="sub">2</div>
<div class="sub">3</div>
</div>
&#13;
►方法2
$('.main').each(function(){
$(this).find('.sub').eq(0).addClass('newclass');
});
工作演示
$('.main').each(function(){
$(this).find('.sub').eq(0).addClass('newclass');
});
&#13;
.newclass{
color:red
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="main">
<div class="sub">1</div>
<div class="sub">2</div>
<div class="sub">3</div>
</div>
<div class="main">
<div class="sub">1</div>
<div class="sub">2</div>
<div class="sub">3</div>
</div>
&#13;
►方法3
$('.main').each(function(){
$(this).find('.sub:eq(0)').addClass('newclass');
});
工作演示
$('.main').each(function(){
$(this).find('.sub:eq(0)').addClass('newclass');
});
&#13;
.newclass {
color: red
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="main">
<div class="sub">1</div>
<div class="sub">2</div>
<div class="sub">3</div>
</div>
<div class="main">
<div class="sub">1</div>
<div class="sub">2</div>
<div class="sub">3</div>
</div>
&#13;
<强>参考强>
答案 1 :(得分:1)
你也可以试试这个:
$('.main div:first-child').addClass('newClass');
我在这里有一个工作演示JSFiddle:https://jsfiddle.net/mayank_shubham/8xeaybhL/1/