When manipulating HTML documents via JavaScript and the DOM, it’s important to watch out for reserved-keyword-crossover issues, where certain HTML element or attribute names are actually reserved keywords in JavaScript.
This is important to know when trying to declare HTML element attributes using JavaScript object.property syntax.
For example, let’s say I want to create this HTML element using JavaScript:
I can’t do something like this:
var div1 = document.createElement("div");
div1.class = "one";
The word “class” is reserved in JavaScript, and although you’re intention is to declare the HTML elements’ “class” attribute, this won’t work.
Instead, you need to do this:
div1.className = "one";
“className” is a subtle alternative that will apply the “class” attribute to any HTML element.
Side-note: I don’t quite understand why it’s called “className,” when “classAttributeValue,” or “classValue” would make more sense.
HTML “for” attribute
Another tricky HTML element attribute to declare in JavaScript is the “for” attribute, which is used in the element. For example:
In JavaScript, we can’t do this:
var label1 = document.createElement("label");
label1.for = "one";
“for” is also a reserved JavaScript keyword.
I bet you’re guessing we need to use forName in JavaScript? Unfortunately, this naming convention is not applicable to any attribute.
Instead, we can try something like this:
var label1 = document.createElement("label");
label1.setAttribute("for", "one");
This seems to work fine in most standards-aware browsers, but Internet Explorer 8 does not seem to support it, so at the moment it’s not a universal solution.
If anyone has another work-around for this, please help resolve this “pain.”
My technical meanderings and other nonsense. Published since 2002. No, really. I'm *that* internet-old. I remember the days of
Apparently with IE you can retrieve the “for” attribute using the pseudonym “htmlFor”. I would never have figured this out on my own, but luckily John Resig had already solved this issue for jQuery and Sizzle (http://bugs.jquery.com/ticket/3794).
This is great!
But how to set the ‘Check One’ through JavaScript?