I have a sidebar, and I want to use JavaScript to check when it is 'active'. Here's my code:
#sidebar {
background: #202020;
color: #fff;
display:inline-block;
}
#sidebar.active {
margin-left: -250px;
}
//Check to see whether sidebar has class 'active'
var sideBar = document.getElementById('sidebar')
console.log(sideBar.className)
if (sideBar.className == ('active')){
console.log('active')
}
else (console.log('not active'))
However, this code is not console.logging anything, and so it's reading "not active" even when the sidebar is clearly activated. What am I doing wrong?
I have a sidebar, and I want to use JavaScript to check when it is 'active'. Here's my code:
#sidebar {
background: #202020;
color: #fff;
display:inline-block;
}
#sidebar.active {
margin-left: -250px;
}
//Check to see whether sidebar has class 'active'
var sideBar = document.getElementById('sidebar')
console.log(sideBar.className)
if (sideBar.className == ('active')){
console.log('active')
}
else (console.log('not active'))
However, this code is not console.logging anything, and so it's reading "not active" even when the sidebar is clearly activated. What am I doing wrong?
Share Improve this question edited Mar 29, 2024 at 17:08 halfer 20.4k19 gold badges109 silver badges202 bronze badges asked Oct 8, 2019 at 21:41 DiamondJoe12DiamondJoe12 1,8239 gold badges52 silver badges104 bronze badges 1- Possible duplicate of Recognizing when sidebar is active or not – Taplar Commented Nov 11, 2019 at 16:16
1 Answer
Reset to default 2The problem you are observing is probably because you pare sidebar.className == ('active')
directly. The className
attribute is a string object which contains the names of all of the classes applied to it. In many cases, there are extra classes automatically added (from various libraries), so checking if it's equal to a single class name often won't do what you want.
The classList
attribute is a DOMTokenList and can more reliably be used for this kind of task. So, for this use case, you could try using sidebar.classList.contains('active')
.
i.e.
var sideBar = document.getElementById('sidebar');
console.log(sideBar.className)
if (sideBar.classList.contains('active')){
console.log('active')
}
else (console.log('not active'))