Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting the HTML <label> 'for' attribute in JavaScript

Tags:

javascript

dom

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

like image 945
Drew Noakes Avatar asked Apr 01 '13 19:04

Drew Noakes


People also ask

What is HTML label for attribute?

The HTML <label> for Attribute is used to specify the type of form element a label is bound to. Syntax: <label for="element_id"> Attribute Values: It contains the value i.e element_id which specify the id of the element that the label is bound to.

Does label need for attribute?

To associate the <label> with an <input> element, you need to give the <input> an id attribute. The <label> then needs a for attribute whose value is the same as the input's id .


1 Answers

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'; 
like image 126
Drew Noakes Avatar answered Sep 22 '22 04:09

Drew Noakes