Javascript - cannot get "getElementsByClassName"

I am trying to understand why my code is not working. Here is the JS part:

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 the HTML part:

<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 do not understand this because if I change this line:

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

at

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

It works!

Why the class selector will not work, but id will? I am trying to get both references with a class showMenuto execute JS.

+4
source share
3 answers

document.getElementsByClassNamereturns a massive list ( HTMLCollectionto be precise) of all elements matching the class name. You probably care about the first element, so try using the following:

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

, :

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

// ...

for ( var i = 0; i < showMenu.length; ++i ) {
    showMenu[i].addEventListener( clickevt, function( ev ) {
        // Your code here
    });
}
+5

, document.getElementsByClassName() node list, .

, , , for .forEach(), n- , :

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

, getElementsByClassName DOM, .

:

for (var i = 0; i < showmenu.length; i++ ) {
    showMenu[i].addEventListener( clickevent, function( ev ) {
        // ...
    });
}

.. :

Array.prototype.forEach.call(showMenu, function(el, i) {
    el.addEventListener( clickevent, function( ev ) {
        // ...
    });
});
+2

All Articles