Categories
JavaScript Answers

How to Find the HTML Label Element Associated with a Given Input with JavaScript?

Spread the love

We can use the labels property of the input to get the label associated with the input.

For instance, if we have the following HTML:

<div>  
  <label for='name'>name</label>  
  <input name='nameInput' id='name'>  
</div>

Then we can get the input with the given label by writing:

const input = document.querySelector('input')  
console.log(input.labels)

We get the input with document.querySelector .

Then we get the label elements for the input with the labels property.

The for attribute value of the label should match up with the id attribute of the input for them to be associated with each other.

input.labels should return a NodeList with the label elements for 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 *