Search code examples
javascriptdom-eventsinternet-explorer-7

Variable won't assign in IE7, but assigns perfectly fine in IE8+ and any other browser


In this slightly lengthy code snippet:

(function() {
    var element = function(str) {
        return document.getElementById(str);
        },

        parent = document.getElementsByTagName('ul')[0].getElementsByTagName('li'),
        len = parent.length,

        swap_slide = function(slide){
            return function(event) {
                event.preventDefault ? event.preventDefault() : event.returnValue = false;
                
                var slides = element('main').getElementsByTagName('div'),
                    len = slides.length;
                for (var i=0; i<len; i++) {
                    slides[i].style.display = 'none';
                }
                slide.style.display = 'block';
            }
        };

    for (var i=0; i<len; i++) {
        var link = parent[i].getElementsByTagName('a')[0],
            slide = element(parent[i].getElementsByTagName('a')[0].getAttribute('href').substr(1));

        if (link.addEventListener) {
            link.addEventListener('click', swap_slide(slide), false);
        } else if (link.attachEvent) {
            link.attachEvent('onclick', swap_slide(slide));
        }
    }

    if (!element(location.hash.substr(1)))
        element('slajd-0').style.display = 'block';
    else 
        element(location.hash.substr(1)).style.display = 'block';
})();

everything works fine in Chrome, Opera, IE9, IE8, Safari, however in IE7 variable slide is null, IE7 reports the error in the function swap_slide, however the error might be somewhere else. I'm not sure if this is a scope error that I caused or is it simple IE retardation?

EDIT: The error IE spits out is:

Error: Unable to get value of the property 'style': object is null or undefined


Solution

  • Change

    getAttribute('href')
    

    to

    getAttribute('href',2)
    

    to get the href as defined and not as a expanded URL

    http://msdn.microsoft.com/en-us/library/ms536429%28v=vs.85%29.aspx