Can’t add hyperlink with onclick to IE using DOM
Last week I was attempting to dynamically add hyperlinks that contained an onclick event to a document. The hyperlink, when written to the browser, would look something like this:
<a href="#" onclick="fireEvent(); return false;">fire away!</a>
and I was using code that looked something like this to produce the links (and yes, I know about real links):
<script>
function createLink(id) {
var node = document.getElementById(id);
var aNode = document.createElement("a");
node.appendChild(aNode);
aNode.setAttribute("href","#");
aNode.setAttribute("onclick", "fireEvent(); return false;");
aNode.appendChild(document.createTextNode("fire away!"));
}
function fireEvent() {
alert('fire!');
}
</script>
<a href="#" onclick="createLink('mytable'); return false;">create link</a>
<table cellpadding="0" cellspacing="0" border="0" width="100%">
<tbody>
<tr>
<td id="mytable"></td>
</tr>
</tbody>
</table>
Running the above code in Firefox worked fine, the fireEvent() method was invoked when you clicked the ‘fire away!’ link. The same exact code in IE didn’t work. Instead, it appeared that IE completely ignored the onclick event and just went with the value of the href attribute. The simple workaround, in this case at least, was to use the innerHTML property of the cell I was adding the link to, so the createLink() function became:
function createLink(id) {
var node = document.getElementById(id);
node.innerHTML = '<a href="#" onclick="fireEvent(); return false;">fire away!</a>';
}
Am I wrong in thinking that this is a bug?
Related:
Early event handlers
Javascript: createElement, innerHTML and IE security zones
can’t put a row into a table in IE using DOM methods
Updated 7/3/2006: My boss Bill sent a note mentioned the behaviors library which uses AOP techniques to reduce what the author calls ’scattering’ and ‘tangling’ and would may also be a solution to the problem mentioned above.
16 Comments