Cannot call method ... of undefined
<p>So I have made this code, it works almost perfectly. The one thing is that setupListener method returns a error at the end, probably it finds a property I don't want to find. I've been struggling with this for a while, but I clearly don't have that much experience with js to solve it. I have setup some console.log methods for debugging. You use this function like this: <code>setupListener(Id or Class or a Tag name as string, event to watch on as string, and an action)</code>; </p>

<p>eg. <code>setupListener('.pun', 'click', function (e){ console.log(e); });</code></p>

<pre><code>    var getElement = function (onStr) {
    if (onStr.indexOf('.') === 0) {
        onStr = onStr.slice(1);
        return document.getElementsByClassName(onStr);
    } 

    if (onStr.indexOf('#') === 0) {
        onStr = onStr.slice(1);
        return document.getElementById(onStr);
    } 

    if (onStr.indexOf('#') !== 0 &amp;&amp; onStr.indexOf('.') !== 0) {
        return document.onStr = document.getElementsByTagName(onStr);
    }
};

var setupListener = function (elementStr, eventStr, action) {
    var tempElement = getElement(elementStr);

        // element a collection and has addEventListener method
        if (tempElement.length &gt; 1 &amp;&amp; tempElement[1].addEventListener) {
            for (var i = 1; tempElement.length &gt;= i; i++) {
                if (typeof(tempElement[i].addEventListener) !== "undefined")
                    console.log('1'); //debugging
                    tempElement[i].addEventListener(eventStr, action);
            }   
        }

        // IE &lt; 9 Support
        // element a collection and has NOT addEventListener method
        else if (tempElement.length  &gt; 1 &amp;&amp; !tempElement[1].addEventListener) {
            for (var i = 1; tempElement.length &gt;= i; i++) {
                if (typeof(tempElement[i].addEventListener) !== "undefined")
                    console.log('2'); // debugging
                    tempElement[i].attachEvent(eventStr, action);
            }
        }

        // element not a collection and HAS addEventListener method
        else if (!tempElement.length &gt; 1 &amp;&amp; tempElement.addEventListener) {
            console.log('3'); // debugging
            tempElement.addEventListener(eventStr, action);
        }

        // element not a collection and has NOT addEventListener method
        // IE &lt; 9 support
        else if (!tempElement.length &gt; 1 &amp;&amp; !tempElement.addEventListener) {
            console.log('4'); // debugging
            tempElement.attachEvent(eventStr, action);
        }

    else { 
     console.log('5'); // debugging
    }
};
</code></pre>
