Arie
Arie

Reputation: 371

How to add a class to the parent div?

I want to show an active menu item, based on the active URL. I have a menu as in the HTML below. I want that if a menu item is clicked, the class active will be added to the .menu_mainitem element.

<div class='row' id='main-items'>
  <div class='menu_mainitem'>
    <a href='https://URL.com/index.php?cat=1' class='click-menu'>1</a>
  </div>
  <div class='menu_mainitem'>
    <a href='https://URL.com/index.php?cat=2' class='click-menu'>1</a>
  </div>
  <div class='menu_mainitem'>
    <a href='https://URL.com/index.php?cat=3' class='click-menu'>1</a>
  </div>
</div>
var current = $(location).attr('href');

$('#main-items a').each(function() {
  var $this = $(this);
  if ($this.attr('href').indexOf(current) !== -1) {
    $this.addClass('active'); 
  }
});

Unfortunately this will add the active class .click-menu but I want to add the class to .menu_mainitem. How can I achieve this?

Upvotes: 1

Views: 523

Answers (1)

Rory McCrossan
Rory McCrossan

Reputation: 337733

You can use either parent() or closest('.menu_mainitem') to get the div you require. My preference is for the latter it is more robust.

var current = $(location).attr('href');

$('#main-items a').each(function(e) {
  var $this = $(this);
  if ($this.attr('href').indexOf(current) !== -1) {
    $this.closest('.menu_mainitem').addClass('active');
  }
});

Also note that you can make the logic a little more succinct by selecting the .menu_mainitem elements directly using toggleClass() with a function to determine if the href of the child a matches your requirements.

var current = $(location).attr('href');

$('.menu_mainitem').toggleClass('active', function() {
  return $(this).find('a').attr('href').indexOf(current) !== -1;
});

Upvotes: 2

Related Questions