Search code examples
javascriptinternet-explorer-7prototypejs

'this' reference to item clicked erroring in ie


For the code below, I am having some issues in IE. The second parameter passed to the function should be a reference to the item clicked. This works fine in FF and Safari, but when I tested it in IE7 it errors. IE appears to get the element (as seen in the console) but whenever I try to do anything with it I get the error:

"Object doesn't support this property or method"

Thanks for the help.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
</head>
<body>  
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/prototype/1.6.0.3/prototype.js"></script>
<script type='text/javascript' src='http://getfirebug.com/releases/lite/1.2/firebug-lite-compressed.js'></script>   
<script language="javascript" type="text/javascript">   
    var Test = {            
        doIt: function(str, btn) {  
            console.log(str);
            console.log(btn);               
            if (btn.hasClassName('red')) {
                console.log('has red');         
            } else {
                console.log('doesn\'t');
            }           
        }   
    };  
</script>   
<a href="#" onClick="Test.doIt('hello', this)" class="red">Test</a> 
</body></html>

Solution

  • The problem is that btn does not automatically have the method hasClassName - that's a Prototype extension.

    To extend your element with prototype extension functions, add this line at the top of doIt():

    btn = $(btn); // Extends element with Prototype functions.
    

    Your code should work from there.