Reputation: 85
I have two classes with nested content, ex:
<div class="tab-content">
<div class='tab-pane'></div>
<div class='tab-pane'></div>
</div>
<div class="tab-content">
<div class='tab-pane'></div>
<div class='tab-pane'></div>
</div>
How do I add the class active on the first tab-pane
for each tab-content
?
Upvotes: 6
Views: 623
Reputation: 19066
You could do this
$(".tab-content").each(function() {
$(this).children(".tab-pane").first().addClass("active");
});
Could also do this with a more specific selector:
$(".tab-content > .tab-pane:first-child").addClass("active");
Upvotes: 4
Reputation: 4646
<div class="tab-content">
<div class='tab-pane'></div>
<div class='tab-pane'></div>
</div>
<div class="tab-content">
<div class='tab-pane'></div>
<div class='tab-pane'></div>
</div>
For that you can see that all of them are in the class tab-content. So you can select that by jquery then find the children of class .tab-pane and then find the first child, and then finnaly add class Active!
$(".tab-content").each(function() {
$(".tab-content").children(".tab-pane").first().addClass("active");
})
And in css..
.active{
color:blue
}
$(".tab-content").each(function() {
$(this).children(".tab-pane").first().addClass("active");
//This wont work: $(".tab-content").children(".tab-pane").first().addClass("active");
//You can check if you want..
});
.active {
color: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="tab-content">
<div class='tab-pane'>1</div>
<div class='tab-pane'>2</div>
</div>
<div class="tab-content">
<div class='tab-pane'>1</div>
<div class='tab-pane'>2</div>
</div>
You have to use $(this) because like what @seammy said...
You changed to an each loop but then you aren't using this, you are just setting the first tab-pane within a tab-content multiple times... rather than for each tab-content
Upvotes: 0
Reputation: 741
If you want to add to the first tab-pane
of both the tab-content
classes - you could do
$('.tab-content').each(function(){
$(this).find('.tab-pane').eq(0).addClass('active');//.first() instead of .eq(0) will also work. eq() just gives you more controll
});
Basically looping over each of your class .tab-content - then selecting necessory child.
Upvotes: 1