Create label tag with attribute "for" with javascript.

Hi!

I'm trying to use Javascript to create a label tag like this:
---------------------------------------------------------
<label for='section'>Section name</label>
---------------------------------------------------------

and I use the Javascript:
===================================
var label = document.createElement('label');
label.for = 'section';
var text = document.createTextNode('Section name');
lable.appendChild(text);
===================================


But when I run this script It get some error at "label.for = 'section';";

So can you correct it for me please?
Thanks
tunhienAsked:
Who is Participating?
 
Cem TürkSenior Software EngineerCommented:
here is a improved version, this function should be called when the body is loaded, btw the differences between your first script and this one are;

when accessing label's for property we have to use label.For not label.for because its CaSe-SeNSiTiVe
we have to append newly created label element to the document with document.body.appendChild(label)

<html><head>
<script language="JavaScript">
<!--
function clabel(fr,txt) {
var label = document.createElement('label');
label.For = fr;
var text = document.createTextNode(txt);
label.appendChild(text);
document.body.appendChild(label); }
//-->
</script>
</head>

<body onload="clabel('section','Section name')">

</body></html>
0
 
Cem TürkSenior Software EngineerCommented:
<html><head>
</head>

<body>
<script language="JavaScript">
<!--
var label = document.createElement('label');
label.For = 'section';
var text = document.createTextNode('Section name');
label.appendChild(text);
document.body.appendChild(label)
//-->
</script>
</body></html>
0
 
tunhienAuthor Commented:
It's so simple!
:-D

Thanks so much
0
 
Cem TürkSenior Software EngineerCommented:
your welcome ;)
0
 
mrichmonCommented:
For others accessing this solution (as I did): the solution stating label.For is actually incorrect.  It should be label.htmlFor (which I found on other sites...)
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.