Find the html tag associated with this input

Say I have an html form. Each input / select / textarea element will have a corresponding <label> with the for attribute set to the identifier of this companion. In this case, I know that each input will have only one label.

Given an input element in javascript - via the onkeyup event, for example - what is the best way to find its associated label?

+80
javascript html label
Nov 12 '08 at 21:55
source share
19 answers

First, scan the page for labels and assign a link to the label from the actual form element:

 var labels = document.getElementsByTagName('LABEL'); for (var i = 0; i < labels.length; i++) { if (labels[i].htmlFor != '') { var elem = document.getElementById(labels[i].htmlFor); if (elem) elem.label = labels[i]; } } 

Then you can just go:

 document.getElementById('MyFormElem').label.innerHTML = 'Look ma this works!'; 

No need for search array :)

+55
Nov 12 '08 at 22:24
source share

If you use jQuery you can do something like this

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

If you are not using jQuery, you will have to look for a label. Here is a function that takes an 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]; } } 
+91
Nov 12 '08 at 22:12
source share

I'm a little surprised that no one seems to know what you were perfectly allowed to do:

 <label>Put your stuff here: <input value="Stuff"></label> 

which will not be picked up by any of the suggested answers, but will correctly mark the input.

Here is the code that takes this case into account:

 $.fn.getLabels = function() { return this.map(function() { var labels = $(this).parents('label'); if (this.id) { labels.add('label[for="' + this.id + '"]'); } return labels.get(); }); }; 

Using:

 $('#myfancyinput').getLabels(); 

Some notes:

  • The code is written for clarity, not for performance. More effective alternatives are available.
  • This code supports retrieving labels of multiple items at a time. If this is not what you want, adapt if necessary.
  • This will not take care of things like aria-labelledby if you want to use it (left as an exercise for the reader).
  • Using multiple shortcuts is a complex business when it comes to support in various user agents and assistive technologies, so test well and use at your own risk, etc. etc.
  • Yes, you can also implement this without using jQuery. :-)
+15
Jan 18 2018-12-18T00:
source share

The HTML5 standard has a labels property that points to labels associated with an input element.

So you can use something like this (support for the native labels property, but backed up to get labels if the browser does not support it) ...

 var getLabelsForInputElement = function(element) { var labels = []; var id = element.id; if (element.labels) { return element.labels; } id && Array.prototype.push .apply(labels, document.querySelector("label[for='" + id + "']")); while (element = element.parentNode) { if (element.tagName.toLowerCase() == "label") { labels.push(element); } } return labels; }; // ES6 var getLabelsForInputElement = (element) => { let labels; let id = element.id; if (element.labels) { return element.labels; } if (id) { labels = Array.from(document.querySelector(`label[for='${id}']`))); } while (element = element.parentNode) { if (element.tagName.toLowerCase() == "label") { labels.push(element); } } return labels; }; 

Even easier if you use jQuery ...

 var getLabelsForInputElement = function(element) { var labels = $(); var id = element.id; if (element.labels) { return element.labels; } id && (labels = $("label[for='" + id + "']"))); labels = labels.add($(element).parents("label")); return labels; }; 
+13
Feb 25 '13 at 6:16
source share

Earlier ...

 var labels = document.getElementsByTagName("LABEL"), lookup = {}, i, label; for (i = 0; i < labels.length; i++) { label = labels[i]; if (document.getElementById(label.htmlFor)) { lookup[label.htmlFor] = label; } } 

Further...

 var myLabel = lookup[myInput.id]; 

Snarky Comment: Yes, you can also do this with jQuery. :-)

+12
Nov 12 '08 at 22:10
source share

with jquery you can do something like

 var nameOfLabel = someInput.attr('id'); var label = $("label[for='" + nameOfLabel + "']"); 
+7
Nov 12 '08 at 22:15
source share
 $("label[for='inputId']").text() 

This helped me get the label of the input element using its identifier.

+2
Sep 05 2018-11-11T00:
source share

The answer from Gijs was the most valuable for me, but, unfortunately, the extension does not work.

Here's a rewritten extension that works, might help someone:

 jQuery.fn.getLabels = function () { return this.map(function () { var parentLabels = $(this).parents('label').get(); var associatedLabels = this.id ? associatedLabels = $("label[for='" + this.id + "']").get() : []; return parentLabels.concat(associatedLabels); }); }; 
+2
Oct 24
source share

If you are ready to use querySelector (and you can, even before IE9, and sometimes IE8!), Another method becomes viable.

If your form field has an identifier and you use the label for attribute, this becomes quite simple in modern JavaScript:

 var form = document.querySelector('.sample-form'); var formFields = form.querySelectorAll('.form-field'); [].forEach.call(formFields, function (formField) { var inputId = formField.id; var label = form.querySelector('label[for=' + inputId + ']'); console.log(label.textContent); }); 

Some noted a few shortcuts; if they all use the same value for the for attribute, just use querySelectorAll instead of querySelector and scroll to get everything you need.

+2
Aug 11 '15 at 12:25
source share

You tried to use document.getElementbyID ('id'), where id is the label identifier, or is it a situation that you do not know which one you are looking for

+1
Nov 12 '08 at 22:10
source share

In fact, it’s much easier to add id to the label in the form itself, for example:

 <label for="firstName" id="firstNameLabel">FirstName:</label> <input type="text" id="firstName" name="firstName" class="input_Field" pattern="^[a-zA-Z\s\-]{2,25}$" maxlength="25" title="Alphabetic, Space, Dash Only, 2-25 Characters Long" autocomplete="on" required /> 

Then you can just use something like this:

 if (myvariableforpagelang == 'es') { // set field label to spanish document.getElementById("firstNameLabel").innerHTML = "Primer Nombre:"; // set field tooltip (title to spanish document.getElementById("firstName").title = "Alfabética, espacio, guión Sólo, 2-25 caracteres de longitud"; } 

javascript really needs to be in the onload function to work.

Just a thought, works great for me.

+1
Nov 26 '13 at 18:29
source share

As already mentioned, (currently) the rating rating does not take into account the possibility of embedding input inside the label.

Since no one has sent a jquery-free answer, here is mine:

 var labels = form.getElementsByTagName ('label'); var input_label = {}; for (var i = 0 ; i != labels.length ; i++) { var label = labels[i]; var input = label.htmlFor ? document.getElementById(label.htmlFor) : label.getElementsByTagName('input')[0]; input_label[input.outerHTML] = (label.innerText || label.textContent); // innerText for IE8- } 

In this example, for simplicity, the lookup table is directly indexed by input HTML elements. It is hardly effective, and you can adapt it as you like.

You can use the form as a basic element or the entire document if you want to get labels for several forms at once.

Valid HTML is not checked (multiple or missing inputs inside labels, missing input with the corresponding htmlFor identifier, etc.), but feel free to add them.

You might want to trim label texts, as in this case input elements are always placed in trailing spaces.

+1
Dec 17 '13 at 11:23
source share

Use the jQuery selector:

 $("label[for="+inputElement.id+"]") 
0
Apr 12 2018-11-21T00:
source share

For future search engines ... The following is a jQuery-ified version of the accepted FlySwat answer:

 var labels = $("label"); for (var i = 0; i < labels.length; i++) { var fieldId = labels[i].htmlFor; if (fieldId != "") { var elem = $("#" + fieldId); if (elem.length != 0) { elem.data("label", $(labels[i])); } } } 

Using:

 $("#myFormElemId").data("label").css("border","3px solid red"); 
0
Aug 19 '11 at 12:56
source share

I know this is old, but I had problems with some solutions and put it together. I tested this on Windows (Chrome, Firefox and MSIE) and OS X (Chrome and Safari) and I think this is the easiest solution. It works with these three types of tagging.

 <label><input type="checkbox" class="c123" id="cb1" name="item1">item1</label> <input type="checkbox" class="c123" id="cb2" name="item2">item2</input> <input type="checkbox" class="c123" id="cb3" name="item3"><label for="cb3">item3</label> 

Using jQuery:

 $(".c123").click(function() { $cb = $(this); $lb = $(this).parent(); alert( $cb.attr('id') + ' = ' + $lb.text() ); }); 

My JSFiddle: http://jsfiddle.net/pnosko/6PQCw/

0
May 21 '14 at 18:07
source share

I made for myself, may be useful for someone: JSFIDDLE

 $("input").each(function () { if ($.trim($(this).prev('label').text()) != "") { console.log("\nprev>children:"); console.log($.trim($(this).prev('label').text())); } else { if ($.trim($(this).parent('label').text()) != "") { console.log("\nparent>children:"); console.log($.trim($(this).parent('label').text())); } else { if ($.trim($(this).parent().prev('label').text()) != "") { console.log("\nparent>prev>children:"); console.log($.trim($(this).parent().prev('label').text())); } else { console.log("NOTFOUND! So set your own condition now"); } } } }); 
0
Nov 26 '14 at 22:53
source share

Am I a little surprised that no one suggests using the CSS relationship method?

in the stylesheet, you can refer to the label from the element selector:

 <style> //for input element with class 'YYY' input.YYY + label {} </style> 

if the flag has the identifier 'XXX' then the label will be found through jQuery:

 $('#XXX + label'); 

You can also apply .find ('+ label') to return the label from the jQuery checkbox element, i.e. useful when looping:

 $('input[type=checkbox]').each( function(){ $(this).find('+ label'); }); 
0
Jan 20 '17 at 5:47
source share
 document.querySelector("label[for=" + vHtmlInputElement.id + "]"); 
0
Jul 20 '17 at 7:16
source share

All other answers are extremely outdated !!

All you have to do is:

 input.labels 

HTML5 has been supported by all major browsers for many years. There is absolutely no reason why you have to do it from scratch on your own or polyfill! Use input.labels and it solves all your problems.

0
Nov 14 '17 at 2:24
source share



All Articles