127

How do you set the for attribute of an HTML <label> element in JavaScript, without using jQuery or any other library?

1 Answer 1

211

Use the htmlFor attribute. I assume it has a slightly cryptic name because for is a keyword in JavaScript:

var label = document.createElement('label');
label.htmlFor = 'some-input-id';
Sign up to request clarification or add additional context in comments.

7 Comments

Would it not be better to just use setAttribute?
@DmitriFarkov, I don't think so. Why would it be better?
I'd say for consistency's sake. Personal disregard for syntactic sugar like this since it implies you are setting an actual property on the object rather than an attribute on an DOM element object. Answers my question though, better only subjectively.
DOM conceptually works with objects and properties. htmlFor is the correct way by setting the DOM element's property. No need to mess with attributes which is what setAttribute does.
Wish I could double up-vote this. I'm using Angular 2 to build a form and needed to update a label's for attribute dynamically. [for] was throwing up an error but [htmlFor] worked a treat. Thank you!
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.