html - Issue checking whether element is 'active' in JavaScript - Stack Overflow

I have a sidebar, and I want to use JavaScript to check when it is 'active'.Here's my

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
Add a ment  | 

1 Answer 1

Reset to default 2

The 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'))

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745127239a4612763.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信