-1

Find the current class from following, whichever data attribute tab has class and add append the current class to similar ID in below div with tab-content

<a class="projects_select tab-link" data-tab="tab-1" href="#tab1"> tab1 </a>
<a class="projects_select tab-link current" data-tab="tab-2" href="#tab2"> tab2 </a>
<a class="projects_select tab-link" data-tab="tab-3" href="#maps"> tab3 </a>

I have following div's having tab-content class.

<div class="tab-content" id="tab-1">Tab-1 </div>
<div class="tab-content" id="tab-2">Tab-2 </div>
<div class="tab-content" id="tab-3">Tab-3 </div>

tried:

$(document).ready(function($) { 
    $('.projects_select').find('current').attr(data-tab);
    $('.tab-content').addClass('current');
});
Nisarg
  • 1,631
  • 6
  • 19
  • 31
  • 2
    You forgot the `.` for your class selector. It's `.current` not `current` that would target a tag instead of a class. – GillesC Feb 07 '19 at 21:53
  • 1
    `find('current')` is looking for `` – epascarello Feb 07 '19 at 21:54
  • `$('.projects_select').find('current').attr(data-tab);` so you are not doing anything with that it would return.... Expect to see something like `var foo = .....` – epascarello Feb 07 '19 at 21:55
  • `.attr(data-tab);` seems like a variable name issue. Or it's just missing surrounding quotes. – Taplar Feb 07 '19 at 22:06

1 Answers1

1

The basic answer is simply a combined class selector, and you need to assign it to a variable:

var myId = $('.projects_select.current').attr(data-tab);

Then, to select a companion element using that:

$('#' + myId).addClass('current');

However, I suggest simplifying to use order (index):

var myIndex = $('.projects_select.current').index();

Then...

$('.tab-content').eq(myIndex).addClass('current');

This eliminates the requirement for IDs and data attributes. If you have more instances of .tab-content on the page, include a class from an element containing both sets of elements:

$('.parent-element .tab-content').eq(myIndex).addClass('current');

https://api.jquery.com/eq/

isherwood
  • 58,414
  • 16
  • 114
  • 157