skip to Main Content

I’m trying to make my HTML more semantic, added IDs to multiple inputs with labels as a part of the same.

However, when I tried to add an ID to an <a> tag and referenced the same in <label>‘s for attribute, it still gives me an error.

<div class="form_item">
  <label for="registrationUrl" class="form_label" title="">Registration URL</label>
  <a id="registrationUrl" href="http://reg:3000" data-url="http://reg:3000" target="_blank" rel="noopener noreferrer" title="http://reg:3000" class="link link--asBtn-md">
    <span>http://reg:3000</span>
  </a>
</div>

The w3 Validator gives me the following error –
Error: The value of the for attribute of the label element must be the ID of a non-hidden form control.

If <a> isn’t a form control, what should be the semantic way to achieve the same result as shown below?

result image

2

Answers


  1. The HTML <label> element’s for attribute is designed to be used with form elements only, such as <input>, <textarea>, <select>, and <button>. The for attribute should be used to bind the label to a specific form control through the ID of the control.

    Since the <a> tag is not a form control, you cannot use a <label> element to associate with it in a semantic HTML way. If you’re trying to provide additional information or context about a link, you might consider using other methods.

    Login or Signup to reply.
  2. Certainly, you can achieve the desired click behavior using inline JavaScript within the HTML. Below is a simplified example:

    <div class="form_item">
      <label class="form_label" onclick="document.getElementById('registrationUrl').click();" style="cursor: pointer;">Registration URL</label>
      <a id="registrationUrl" href="http://reg:3000" target="_blank">
        http://reg:3000
      </a>
    </div>
    

    Note:

    • Accessibility & Semantics: While this method provides the desired
      behavior, it is not a recommended practice in terms of semantic HTML
      and accessibility. A <label> element is not semantically intended to
      be used with an anchor (<a>) element
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search