Published at
Updated at
Reading time
2min
This post is part of my Today I learned series in which I share all my web development learnings.

Today I dicovered an MDN page that describes the labels property of textarea elements. I haven't used this property before and started playing around with it.

It turns out that input elements (and textareas) hold references to their connected labels.

Assuming you wrote the HTML below, you can access the label element using labels. labels then returns a NodeList with the connected elements.

<label for="foo">Some input</label>
<input type="text" id="foo">

<script>
  console.log(document.getElementById('foo').labels);
  // NodeList (1) [label]
</script>

I never had a use case for this property, but I bet that accessibility linters use the labels property quite heavily to validate accessible forms. Label your input elements, friends! They are essential to make your forms accessible.

When creating forms, I prefer to place the input elements inside label elements because it increases the clickable area that will focus the input.

Unfortunately, if you place your input elements inside labels, you can't omit the for attribute because not every screenreader supports "wrapping labels".

I was delighted to find out that the labels property works fine with this approach, too!

<label>
  <span>
    Some input
  </span>
  <input type="text" id="foo">
</label>

<script>
  console.log(document.getElementById('foo').labels);
  // NodeList (1) [label]
</script>

It even returns multiple labels if you're using several labels for one input element.

<label>
  <span>
    Some input
  </span>
  <input type="text" id="foo">
</label>
<label for="foo">Some input</label>

<script>
  console.log(document.getElementById('foo').labels);
  // NodeList (2) [label, label]
</script>

And that's the trivia for today! Maybe you're writing an accessibility linter right now – then labels can be helpful. :)

If you enjoyed this article...

Join 5.4k readers and learn something new every week with Web Weekly.

Web Weekly — Your friendly Web Dev newsletter
Stefan standing in the park in front of a green background

About Stefan Judis

Frontend nerd with over ten years of experience, freelance dev, "Today I Learned" blogger, conference speaker, and Open Source maintainer.

Related Topics

Related Articles