Polecalex
Polecalex

Reputation: 373

Selecting an element within a parent element of another

I want to find out how, I am able to select an element which is outside the element which has been clicked.

<li class="nav-item dropdown">
  <a href="javascript;" class="menu-toggle">
    <i class="fa fa-server"></i>
    <span>Server</span>
  </a>
  <ul class="dropdown-menu">
    <li>
      <a>
        <i class="fa fa-home"></i>
        <span>Item one</span>
      </a>
    </li>
  </ul>
</li>

Within the code, I want to make it so when the user clicked the button, which will trigger the link, it will then display the "dropdown-menu", by adding the class "open" to list-item "nav-item dropdown".

I have more than one dropdown menu within the navigation too, so I cannot just simple select "dropdown-menu" and then make it visible, as it will make all of the dropdown menu's visible. So is there any way of doing this? I have tried to select the element, but it just selects them all, and I just cannot get my head around it.

Much appreciated.

Upvotes: 1

Views: 38

Answers (3)

matt.
matt.

Reputation: 2369

You can select the target parent using closest or parents methods, then just find the dropdown and add the class.

Example:

$('.menu-toggle').on('click', function() {
  e.preventDefault();

  $(this).closest('.nav-item dropdown').find('.dropdown-menu').toggleClass('open');
});

Upvotes: 0

Miguel
Miguel

Reputation: 20633

Vanilla JS solution

document.querySelectorAll('.menu-toggle').forEach(element => {
    element.addEventListener('click', event => {
       event.preventDefault();
       element.parentNode.querySelector('.dropdown-menu').classList.toggle('open');
  });
});

JSFiddle Demo: https://jsfiddle.net/hp1debw7/1/

Upvotes: 1

Nenad Vracar
Nenad Vracar

Reputation: 122087

You can use $(this).next() DEMO

$('.menu-toggle').click(function(e) {
  e.preventDefault();
  $(this).next('.dropdown-menu').toggleClass('open');
})

Upvotes: 4

Related Questions