Search code examples
javascriptjquerycssdropdown

Multiple Bootstrap dropdown in same div class


Is it possible to have multiple dropdown menus in the same nav class in bootstrap, without putting each menu item in a separate div?

What is happening is that when I click on the dropdown menu , the same dropdown opens up every time( I have two dropdowns for two separate menu items)

I have tried using data-target to open only the dropdown with a specific id but this returns a console error.

  <nav>
      <a>Menu item 1</a>
      <a>Menu item 2</a>
      <a class="dropdown dropdown-toggle" href="#" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Menu item 3(dropdown menu 1)</a>
        <div class="dropdown-menu" aria-labelledby="dropdown">
          <a class="dropdown-item" href="/">dropdown item 1</a>     
        </div>


      <a class="dropdown dropdown-toggle" href="#" style= "display:none;" id="certdropdown" data-toggle="dropdown" data-target="#dropdown2" aria-haspopup="true" aria-expanded="false">Menu item 3 ( dropdown menu 2)</a>
      <div class="dropdown-menu" aria-labelledby="dropdown" id ="dropdown2">
          <a class="dropdown-item" href="/">dropdown item 1</a>     
        </div></nav>

If i separate both menu items in separate div, it works but my css gets ruined


Solution

  • No, it's not possible to have two dropdown menus inside the same div. They need to be separated since the code to toggle them looks for the first element in the parent div of the button/anchor. So if they are in the same parent div only the first will be toggled.

    Since you haven't provided what part of your CSS gets ruined, I'm gonna guess two problems you might encounter with this.

    1. The dropdown buttons gets wrapped to the next row.
    2. You're selecting links inside your nav by doing nav > a, which ignores the links inside the <div class="dropdown"></div> or you're selecting links inside your nav by doing nav a, which includes the links inside the dropdown-menu.

    First solution:

    If your dropdown buttons/links gets placed on their own row, it's because they have the display value of block. Add the class d-inline to the <div class="dropdown"> to fix this.

    Second solution:

    Select and style your links inside the nav with this code:

    nav a:not(.dropdown-item) {
      // styling
    }
    

    This will ignore the links inside the dropdown but style all other links.


    If you're having some other problem with your CSS please explain what it is and I will try to help you.