最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin1浏览0评论

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'))
发布评论

评论列表(0)

  1. 暂无评论