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.
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 .
htmlFor property reflects the value of the for content property. That means that this script-accessible property is used to set and read the value of the content property for , which is the ID of the label's associated control element.
<input type="search"> <input type="tel"> <input type="text">
You shouldn't rely on the order of elements by using prev
or next
. Just use the for
attribute of the label, as it should correspond to the ID of the element you're currently manipulating:
var label = $("label[for='" + $(this).attr('id') + "']");
However, there are some cases where the label will not have for
set, in which case the label will be the parent of its associated control. To find it in both cases, you can use a variation of the following:
var label = $('label[for="' + $(this).attr('id') + '"]');
if(label.length <= 0) {
var parentElem = $(this).parent(),
parentTagName = parentElem.get(0).tagName.toLowerCase();
if(parentTagName == "label") {
label = parentElem;
}
}
I hope this helps!
There are two ways to specify label for element:
So, the proper way to find element's label is
var $element = $( ... )
var $label = $("label[for='"+$element.attr('id')+"']")
if ($label.length == 0) {
$label = $element.closest('label')
}
if ($label.length == 0) {
// label wasn't found
} else {
// label was found
}
As long and your input
and label
elements are associated by their id
and for
attributes, you should be able to do something like this:
$('.input').each(function() {
$this = $(this);
$label = $('label[for="'+ $this.attr('id') +'"]');
if ($label.length > 0 ) {
//this input has a label associated with it, lets do something!
}
});
If for
is not set then the elements have no semantic relation to each other anyway, and there is no benefit to using the label tag in that instance, so hopefully you will always have that relationship defined.
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