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

edt picture edt · Jun 19, 2009 · Viewed 153.6k times · Source

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>

Answer

Hugoware picture Hugoware · Jun 19, 2009

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>