How do you set the for attribute of an HTML <label> element in JavaScript, without using jQuery or any other library?
1 Answer
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';
7 Comments
Dmitri Farkov
Would it not be better to just use setAttribute?
Drew Noakes
@DmitriFarkov, I don't think so. Why would it be better?
Dmitri Farkov
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.
Fabrício Matté
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.cbros2008
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!
|