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
?
Different Elements Can Share Same Class Different HTML elements can point to the same class name.
The :first-child selector allows you to target the first element immediately inside another element. It is defined in the CSS Selectors Level 3 spec as a “structural pseudo-class”, meaning it is used to style content based on its relationship with parent and sibling content.
The addClass() method adds one or more class names to the selected elements. This method does not remove existing class attributes, it only adds one or more class names to the class attribute. Tip: To add more than one class, separate the class names with spaces.
You could do this
JSFiddle
$(".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");
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With