Manipulating HTML with JavaScript: <label> element "for" attribute

Posted by Matt Thommes on November 18, 2009 | Post type: Pain | Status: Unresolved

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:

<div class="one"></div>

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 <label> "for" attribute

Another tricky HTML element attribute to declare in JavaScript is the "for" attribute, which is used in the <label> element. For example:

<label for="one">Check One</label>

<input type="checkbox" id="one" />

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."

About the author(s)

Matt Thommes is an independent publishing enthusiast, mobile blogger, content creator, informative writer, web developer from a suburb of Chicago. Never one to conform, Matt intends to promote the effect the web has on our lives, in an effort to intensify, instruct, and clarify all that is happening around us.

Comments

Note: Comments may be viewed by authors, but if you have a more specific question you'd like to ask them, please email matt.thommes@paininthetech.com.