Selecting the first child from one class and adding the class name
I have two classes with nested content, for example:
<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 to add a class to the first tab-pane for each tab-content ?
If you want to add tab-content classes to the first tab-pane - 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 .tab class content, and then choosing the right child.
<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> To do this, you can see that they are all in the class-content of the class. So you can select this using jquery, then find the children of the .tab-pane class, then find the child of the first , and then finalize the Active class!
$(".tab-content").each(function() { $(".tab-content").children(".tab-pane").first().addClass("active"); }) And in css ..
.active{ color:blue } Snipet
$(".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 should use $ (this) because, as @seammy said ...
You changed every cycle, but then you donβt use it, you just set the first tab bar as a contribution several times ... and not for each tab content