How to find the HTML label associated with a given input with JavaScript?

Spread the love

Sometimes, we want to find the HTML label associated with a given input with JavaScript.

In this article, we’ll look at how to find the HTML label associated with a given input with JavaScript.

How to find the HTML label associated with a given input with JavaScript?

To find the HTML label associated with a given input with JavaScript, we get all the labels and check the value of their for attribute.

For instance, we write

const findLableForControl = (el) => {
  const idVal = el.id;
  const labels = document.getElementsByTagName("label");
  for (const label of labels) {
    if (label.htmlFor === idVal) {
      return label;
    }
  }
};

to define the findLableForControl function.

In it, we get all the labels with getElementByTagName.

Then we use a for-of loop to loop through them.

In it, we get the for attribute value with the htmlFor property.

And we compare that with the input’s ID stored in idVal.

If label.htmlFor equals idVal then we return the label.

Conclusion

To find the HTML label associated with a given input with JavaScript, we get all the labels and check the value of their for attribute.

Leave a Reply

Your email address will not be published. Required fields are marked *