jQuery - select the associated label element of a input field
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.
There are two ways to specify label for element:
- Setting label's "for" attribute to element's id
- Placing element inside label
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
}
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!