Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find html label associated with a given input

Let's say I have an html form. Each input/select/textarea will have a corresponding <label> with the for attribute set to the id of it's companion. In this case, I know that each input will only have a single label.

Given an input element in javascript — via an onkeyup event, for example — what's the best way to find it's associated label?

like image 970
Joel Coehoorn Avatar asked Nov 12 '08 21:11

Joel Coehoorn


People also ask

How do you associate a label with an input?

There are two ways to pair a label and an input. One is by wrapping the input in a label (implicit), and the other is by adding a for attribute to the label and an id to the input (explicit). Think of an implicit label as hugging an input, and an explicit label as standing next to an input and holding its hand.

How do I get element labels?

Use the textContent property to get the text of a label element, e.g. const text = label. textContent . The textContent property will return the text content of the label and its descendants. If the element is empty, an empty string is returned.

How do you access labels in HTML?

You ask the input tag to behave like a label. You can directly access your label tag and change it. Just add an id to your label tag and then insert this id into your getElementById .

How do you display input and label on the same line?

Using float and overflow attributes: Make a label and style it with float attribute. Now set the label float(position) left or right according to your requirement. This will align your label accordingly. Overflow property for input is used here to clip the overflow part and show the rest.


1 Answers

If you are using jQuery you can do something like this

$('label[for="foo"]').hide (); 

If you aren't using jQuery you'll have to search for the label. Here is a function that takes the element as an argument and returns the associated label

function findLableForControl(el) {    var idVal = el.id;    labels = document.getElementsByTagName('label');    for( var i = 0; i < labels.length; i++ ) {       if (labels[i].htmlFor == idVal)            return labels[i];    } } 
like image 103
TonyB Avatar answered Nov 16 '22 00:11

TonyB