CreateTextNode And IE7
Nov 30, 2006
When running this code in IE7:
function insertScript() {
var newScript = document.createElement('script');
newScript.type = "text/javascript";
var s = document.createTextNode("alert('hi');");
newScript.appendChild(s); // problem line
document.getElementById("myDiv").appendChild(newScript);
}
window.onload=insertScript;
I get this error:
Unexpected call to method or property access
And a pointer that points to the newScript.appendChild(s) line.
Am I using createTextNode incorrectly or is IE7 getting it wrong?
The function, as written, works correctly in FF2.0, Opera9 and AIUI,
Safari1.3.2 Its an attempt to get around Safari not supporting the
setting of the .text property of a script element. If IE7 simply won't
create the text and append it then feature testing for createTextNode
won't work. So, I came up with the idea of attempting to set the .text
property with a variable definition then reading that variable. If it is
set, then use the .text property. If it isn't set, then use
createTextNode. Not sure how reliable it is so I thought about using an
IE conditional to isolate IE and go based on that but it reeks of
browser detection.
View 50 Replies
Feb 25, 2006
Modified with a newer version since it was first posted. Some comments may refer to older versions.
function entity(str, mode) {
str = (str) ? str : "";
mode = (mode) ? mode : "string";
var e = document.createElement("div");
e.innerHTML = str;
if (mode == "numeric") {
return "&#" + e.innerHTML.charCodeAt(0) + ";";
}
else if (mode == "utf16") {
var un = e.innerHTML.charCodeAt(0).toString(16);
while (un.length < 4) un = "0" + un;
return "u" + un;
}
else return e.innerHTML;
}
entity() has two parameters:
- entity: is a string which can be either a named entity (»), numeric entity (»), UTF-16 value (u00bb), or even the character itself (»).
- mode: is an optional value that can be 'string', 'numeric', or 'utf16'. This tells the function what to return the value as. Defaults to 'string'.
You'd use it like this:
// String mode
var div = document.createElement('div');
var text = document.createTextNode('Parent '+entity('»')+' Child');
div.appendChild(text);
// Numeric mode
var description = "The entity for » is "+entity('»', 'numeric');
// UTF-16 mode
var description = "The UTF-16 value for » is "+entity('»', 'utf16');
View 3 Replies
View Related
Sep 22, 2005
Is there a way to get © to translate when using createTextNode ?
div.appendChild(document.createTextNode('Copyright © 1998-'+(new Date().getFullYear())+', SomeCompany'));
View 2 Replies
View Related