1

I want to make toggle nav but unfortunately not working

function navtoggle(){
            document.getElementsByClassName('sidebar').classList.toggle('active');
        }
    </script>
.sidebar.active {
    width:0px;
}
1
  • 1
    you are using document.getElementsByClassName.. and it returns a node list.. try document.querySelector('.sidebar') Commented Jun 2, 2019 at 15:51

2 Answers 2

2

document.getElementsByClassName('sidebar').classList is a HTMLCollection, you must loop through it or pick a specific index

function navtoggle(){
    document.getElementsByClassName('sidebar')[0].classList.toggle('active');
}
.active {
  color: red;
}
<div class="sidebar">Hello</div>
<button onClick="navtoggle();">Click Me</button>

Sign up to request clarification or add additional context in comments.

Comments

0

document.getElementsByClassName() will return a HTMLCollection instead of the single sidebar element you're trying to target. Because classList isn't a property of HTMLCollection, you'll simply get a TypeError when trying to toggle a class on this collection.

If you are sure there is only one element with .sidebar on the page, or that the sidebar you're trying to target is the first in the DOM, you could use document.getElementsByClassName('sidebar')[0]. An alternative approach would be to use document.querySelector('.sidebar'), where you can also pass a more specific selector, such as document.querySelector('aside.sidebar'), to ensure you've selected the right element. For example:

function navtoggle() {
  document.querySelector('aside.sidebar').classList.toggle('active');
}
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  font-family: sans-serif;
}

body {
  width: 100vw;
  height: 100vh;
}

.sidebar {
  background: #CCC;
  width: 15%;
  height: 100%;
  padding: 1rem;
  overflow: hidden;
}

.sidebar.active {
  width: 0;
  padding: 0;
}

main {
  position: absolute;
  right: 0;
  top: 0;
  width: 85%;
  height: 100%;
  padding: 1rem;
}

button {
  padding: .5rem;
  margin-top: .5rem;
}
<aside class="sidebar">
  This is the sidebar
</aside>

<main>
  This is not the sidebar <br>
  <button onclick="navtoggle()">Toggle the sidebar</button>
</main>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.