Hopefully this one doesn't go off the beaten track too much - but I was wondering what the quickest method is in jQuery for targeting another element (that is a close relative of $(this).whatever
) with the same data id attribute. I currently have the following markup (if you use the latest Bootstrap you'll notice that this is just a simple card with nav headings):
<div class="card text-center">
<div class="card-header pb-0">
<ul id="contactGroups" class="nav justify-content-center nav-tabs card-header-tabs">
<li class="nav-item" data-id="1">
<a class="nav-link active" href="#">Contact Us</a>
</li>
<li class="nav-item" data-id="2">
<a class="nav-link" href="#">Business Enquiries</a>
</li>
<li class="nav-item" data-id="3">
<a class="nav-link" href="#">Follow Us</a>
</li>
</ul>
</div>
<div class="card-body active" data-id="1">
<h5 class="card-title">Special title treatment</h5>
<p class="card-text">With supporting text below as a natural lead-in to additional content.</p>
<a href="#" class="btn btn-primary">Go somewhere</a>
</div>
<div class="card-body hidden" data-id="2">
<h5 class="card-title">Special title treatment</h5>
<p class="card-text">With supporting text below as a natural lead-in to additional content.</p>
<a href="#" class="btn btn-primary">Go somewhere</a>
</div>
<div class="card-body hidden" data-id="3">
<h5 class="card-title">Special title treatment</h5>
<p class="card-text">With supporting text below as a natural lead-in to additional content.</p>
<a href="#" class="btn btn-primary">Go somewhere</a>
</div>
</div>
As you can see in the above markup I have data-id attributes added to the list elements - I want to then go in and find it's corresponding data-id (the ones with the card-body active or card-body hidden) so I can begin to play with them. However (!!) I don't want to select on some arbitary #id or .class that I assign. How would I go about doing this?
My jQuery thus far is as follows (however, this only flips the current class from non-active (or no class) to the active class giving the tab swop illusion:
$('#contactGroups').each(function(){
$(this).find('li').each(function(){
$(this).on('click', function() {
$('#contactGroups').find('.active').removeClass('active');
$(this).find('a').addClass('active');
})
});
});
Any thoughts would be greatly appreciated.