«   Previous tip Next tip   »

JavaScript: Access your label elements from a HTML input element

Last updated: 2nd March 2023


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" />

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

«   Previous tip Next tip   »

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