How to Set OnClick attribute with value containing function in ie8?

javascript, onclick, setattribute

Solution

You don't need to use setAttribute for that - This code works (IE8 also)

<div id="something" >Hello</div>
<script type="text/javascript" >
    (function() {
        document.getElementById("something").onclick = function() { 
            alert('hello'); 
        };
    })();
</script>

Problem

My goal is to change the `onclick` attribute of a link. I can do it successfully, but the resulting link doesn't work in ie8. It does work in ff3. For example, this works in Firefox 3, but not IE8. Why? ``` <p><a id="bar" href="#" onclick="temp()">click me</a></p> <script> doIt = function() { alert('hello world!'); } foo = document.getElementById("bar"); foo.setAttribute("onclick","javascript:doIt();"); </script> ```

Original source