Reputation: 1809
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?
Upvotes: 1
Views: 12479
Reputation: 6015
The problem you are observing is probably because you compare 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'))
Upvotes: 2