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.