Home > database >  How to make a navbar I've created to toggle using the document.querySelector = classList.toggle
How to make a navbar I've created to toggle using the document.querySelector = classList.toggle

Time:07-12

Here is a code of how I've named the navbar component classes and the code for the javascript toggle function

    <div class = "sidebar">
        <div class = "logo_content">
            <div class = "logo">
                <i class = "bx bxl-c-plus"></i>
    
                <div class = "logo_name">Pollster</div>
            </div>
            <button onclick = 'nav_toggle()' class = "bx bx-menu" id = "btn" ></button>
        </div>



    <script>
       function nav_toggle(){
        document.querySelector('sidebar #btn').classList.toggle('active');
       }

    </script>
        `

CodePudding user response:

The correct selector for that element was supposed to be .sidebar #btn because you are selecting an element with the id btn as a child of an element having the sidebar class.

But since the id is supposed to be unique in the whole document, you could just use #btn.

It actually sounds strange that you really needed to select the button element and toggle a given class, so in case you meant to select a different element just make it more clear. My assumption was based on your selector sidebar #btn which had just one flaw: it was trying to select an element with id btn nested inside an element of type sidebar.

function nav_toggle(){
  document.querySelector('.sidebar #btn').classList.toggle('active');
}
.active{
  background: red;
}
<div class = "sidebar">
  <div class = "logo_content">
    <div class = "logo">
      <i class = "bx bxl-c-plus"></i>
      <div class = "logo_name">Pollster</div>
    </div>

    <button onclick='nav_toggle()'  id="btn">Toggle</button>
  </div>
</div>

CodePudding user response:

CSS STYLE

   <style>
      .mystyle {
        width: 100%;
        padding: 25px;
        background-color: coral;
        color: white;
        font-size: 25px;
        box-sizing: border-box;
      }
    </style>

HTML ELEMENT

    <div >
      <div >
        <div >
          <i ></i>
          <div >Pollster</div>
        </div>
        <button onclick="nav_toggle()"  id="btn">
          toogle button
        </button>
      </div>
    </div>

    <div  id="sidebar">side bar content</div>

SCRIPT

   <script>
      function nav_toggle() {
        var element = document.getElementById("sidebar");
        element.classList.toggle("mystyle");
      }
    </script>

in this way you can toggle element by selecting id

  • Related