Given the following code:
<!DOCTYPE html> <!-- HTML5 -->
<html>
<head>
<meta http-equiv="Expires" content="Fri, Jan 01 1900 00:00:00 GMT">
<meta http-equiv="Pragma" content="no-cache">
<meta http-equiv="Cache-Control" content="no-cache">
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<meta http-equiv="content-language" content="en">
<title>Untitled</title>
<script type='text/javascript'>
function createTableRow() {
var tr = document.createElement("tr");
var strWork = "<tr onmouseover='this.style.cursor=\"pointer\";'";
strWork += " onmouseout='this.style.cursor=\"auto\";'";
strWork += " onclick='ShowClick(this);'";
strWork += " id='TestCell'><td>Test!</td></tr>";
alert(strWork);
tr.outerHTML = strWork;
return tr;
}
function BuildTable() {
var table = document.createElement("table");
table.appendChild(createTableRow());
return table;
}
function ShowClick(obj) {
alert(obj.id);
}
</script>
</head>
<body onload='alert(BuildTable().outerHTML);'>
</body>
</html>
The first "alert" dialog shows the tag as I want it to be formed, however, the "onload=alert" line returns the result "<table><tr></tr></table>".
What am I doing wrong? Why aren’t these events binding to the TR tag?
Also, I’d like to add that I originally assigned the events using JavaScript i.e.:
tr.onclick = function() { ShowClick(this); };
But had the exact same result…
I really don’t get it, and I can’t find any discussion about the problem anywhere… any help would be greatly appreciated!
Your code throws a
NO_MODIFICATION_ALLOWED_ERRin the JavaScript console. The W3C spec has this to say:The same thing happens in your code. You’re setting the
tr‘souterHTMLbefore you’ve appended it to another Node (e.g. thetable). That’s why itsouterHTMLcan’t be changed.The easiest solution is not to use
outerHTML. Try your original approach:Note that when you
alert(orconsole.log) thetable‘souterHTML, you’ll see something like this:But don’t let that fool you. The event handlers don’t show up, but that’s because they are attached directly to the DOM node, thus bypassing the HTML. Rest assured that they work perfectly.
To see for yourself, try this live demo: jsbin.com/oterit/1/edit