Categories
JavaScript Answers

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

Spread the love

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

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

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

To find HTML label associated with a given input with JavaScript, we can select the label elements and then loop through them to find the one with the htmlFor property equally the ID of the input.

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 that takes the el input element.

In it, we get the id of the el element.

Then we select all the labels with getElementsByTagName.

Next we loop through the labels and find the one with the htmlFor property equaling idVal.

htmlFor has the value of the for attribute of the label.

Conclusion

To find HTML label associated with a given input with JavaScript, we can select the label elements and then loop through them to find the one with the htmlFor property equally the ID of the input.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

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