Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selecting from same class the first child and adding a class name

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?

like image 461
Nodos Avatar asked Mar 26 '16 20:03

Nodos


People also ask

Can you use the same class name on multiple elements?

Different Elements Can Share Same Class Different HTML elements can point to the same class name.

How do you write first child in SCSS?

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.

What does add class do?

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.


2 Answers

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");
like image 143
Dallas Avatar answered Oct 16 '22 05:10

Dallas


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.

like image 1
Anubhab Avatar answered Oct 16 '22 04:10

Anubhab