JavaScript: Access your label elements from a HTML input element

Last updated: March 2, 2023

Introduction

Given a form input, you can get its associated labels with:

const labels = $("#name").labels;
labels[0].textContent; // Enter your name

Or using destructing:

const [{ textContent }] = $("#name").labels;
textContent; // Enter your name

Assumes HTML like this:

<form method="get">
	<label for="name">Enter your name: </label>
	<input type="text" name="name" id="name" />
</form>

Tip: $('#name') is a DevTools Console Panel alias. It works the same as document.querySelector('#name').

Sign up to receive a developer tip, in the form of a gif, in your inbox each week