RSS Amplifier

a5h blog posts (software eng) · May 1, 2022

Interesting HTML (web API) Topics

0
Sign in to vote or save

a5h.dev

Last updated on May 2022

WIP post, with some interesting topics about web APIs/HTML elements/etc.

Get the label for an input easily

I never knew that form elements such as <input> (HTMLInputElement) has a labels attribute, which is a list (DOMTokenList) of associated labels.

This is a demo, with the code below it:

Your email address

The code is something along the lines of:

<!-- the label I want to get: -->
<label for="demo-email">Your email address</label>
<!-- the input I want the label for: -->
<input id="demo-email" />
<!-- button to trigger the alert() with the label textContent -->
<button id="show-label">Show label</button>
<script>
function clickHandler() {
    // the <input> element:
    const inputElement = document.getElementById('demo-email');
    const labels = inputElement.labels; // << the bit i'm showing
    const firstLabelElement = labels[0];
    const labelText = firstLabelElement.textContent
    alert(`Associated label for the input: "${labelText}"`);
}
document.querySelector('#show-label')
        .addEventListener('click', clickHandler)
</script>

Read the original on a5h.dev

Comments

Nothing yet. Say the first thing.

    Sign in to join the conversation.