JavaScript – Fix getElementsByClassName Not Working

htmljavascriptjqueryprogrammingwebsites

Im struggling to figure out why my code is not working.
Here is part of the JS:

function init() {
    var showMenu = document.getElementsByClassName('showMenu'),
        perspectiveWrapper = document.getElementById( 'perspective' ),
        container = perspectiveWrapper.querySelector( '.container' ),
        contentWrapper = container.querySelector( '.wrapper' );

    showMenu.addEventListener( clickevent, function( ev ) {
        ev.stopPropagation();
        ev.preventDefault();
        docscroll = scrollY();
        // change top of contentWrapper
        contentWrapper.style.top = docscroll * -1 + 'px';
        // mac chrome issue:
        document.body.scrollTop = document.documentElement.scrollTop = 0;
        // add modalview class
        classie.add( perspectiveWrapper, 'modalview' );
        // animate..
        setTimeout( function() { classie.add( perspectiveWrapper, 'animate' ); }, 25 );
    });

Here is part of the HTML:

<div id="topBar">
    <h1>Company</h1>
    <a href="#" class="entypo-menu showMenu"></a>
</div>

<div class="line"></div>

<div id="fixedBar">
    <h1>Company</h1>
    <a href="#" class="entypo-menu showMenu"></a>
</div>

For some reason when I load the page, I get this error:

TypeError: undefined is not a function (evaluating 'showMenu.addEventListener')

I don't understand this because if I change this line:

var showMenu = document.getElementsByClassName('showMenu'),

to:

var showMenu = document.getElementById( 'showMenu' ),

It does work!

Why won't the class selector work but the id one will?

Thanks.

Best Answer

Try:

var showMenu = document.getElementsByClassName('showMenu')[0]

The s in Elements in the function name indicates more than elements may be matched.

var showMenu = document.getElementsByClassName('showMenu')
...

for(var i = 0, j = showMenu.length; i < j; i++)
{
    showMenu[i].addEventListener( clickevent, function( ev ) {
        ev.stopPropagation();
        ev.preventDefault();
        docscroll = scrollY();
        // change top of contentWrapper
        contentWrapper.style.top = docscroll * -1 + 'px';
        // mac chrome issue:
        document.body.scrollTop = document.documentElement.scrollTop = 0;
        // add modalview class
        classie.add( perspectiveWrapper, 'modalview' );
        // animate..
        setTimeout( function() { classie.add( perspectiveWrapper, 'animate' ); }, 25 );
    });
}
Related Topic