Margareth Didyk
Margareth Didyk

Reputation: 87

jQuery target element by its id attribute using the href attribute of another element?

When the user clicks on a div.nav element jQuery changes its class to active. Currently it sets display: block to all three of the div.content elements. I want jQuery to only set the display: block property on the div.content elements that have the active class. Here is my code:

$('div.nav').on('click', 'a:not(.active)', function() {
    $(this).addClass('active').siblings().removeClass('active')
});

$("div.nav a").click(function(){
    $("div.content").css("display", "block");
});
<div class="nav">
    <a class="active" href="#1"></a>
    <a href="#2"></a>
    <a href="#3"></a>
</div>
<div id="1" class="content active"></div>
<div id="2" class="content"></div>
<div id="3" class="content"></div>
.content {
    display: none;
}
.content.active {
    display: block;
}

What can I do here?

Upvotes: 2

Views: 911

Answers (2)

Josh Crozier
Josh Crozier

Reputation: 240928

If you're trying to add/remove the class from the corresponding .content elements, you can retrieve the href attribute of the clicked a element in order to form the selector to select the .content element. For instance:

Working Example Here

$('div.nav').on('click', 'a:not(.active)', function() {
  var selector = this.getAttribute('href');

  $(this).addClass('active').siblings().removeClass('active');
  $(selector).addClass('active').siblings('.content').removeClass('active');
});

Upvotes: 3

HaukurHaf
HaukurHaf

Reputation: 13796

Change this line:

$("div.content").css("display", "block");

To this:

$("div.content.active").css("display", "block");

If I understand you correctly. It will only target div elements which have both the content and the active classes.

Upvotes: 2

Related Questions