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?
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.
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.
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 .
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.
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]; } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With