简体   繁体   中英

Click HTML element A and add Class on B with pure JavaScript

I can't see what I'm doing wrong here.. Can anyone help please?

JavaScript:

function toggleMainNav() {
        var navLink = document.getElementsByClassName('nav_link')[0];
        var mainNav = navLink.nextSibling;
        if ( mainNav.className.match(/(?:^|\s)inactive(?!\S)/) ){
            mainNav.className = 'active';
        } else{
            mainNav.className = 'inactive';
        }
    }

    document.getElementsByClassName('nav_link')[0].addEventListener( 'click' , toggleMainNav );

this is the HTML:

<a class="nav_link">☰ Menu</a>
<ul class="inactive">
</ul>

nextSibling will be a text node containing whitespace. Either scan until you get nodeType === 1 or use nextElementSibling (but check whether it's supported on your target browsers).


Side note: getElementsByClassName has worse support than querySelector / querySelectorAall (IE8 has the latter but not the former, for instance), so you might consider using those instead.

Side note 2: IE8 also doesn't have addEventListener .

Side note 3: If you hook up your handler via addEventListener , within the handler this will already be the first nav_link , so you don't have to look it up again.

Side note 4: Some older browsers will fail if you don't give the third argument to addEventListener (it didn't used to be optional). To be broadly-compatible, be sure to include the false at the end.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM