Home > Mobile >  Constraint Validation API: Questions Regarding Element Selector
Constraint Validation API: Questions Regarding Element Selector

Time:04-16

What exactly is the [0] in this bit of code?

Why is it there?

What does it do?

Thank you!

const form  = document.getElementsByTagName('form')[0];


<form novalidate>
    <p>
      <label for="mail">
        <span>Please enter an email address:</span>
        <input type="email" id="mail" name="mail" required minlength="8">
        <span  aria-live="polite"></span>
      </label>
    </p>
    <button>Submit</button>
  </form>

CodePudding user response:

const form = document.getElementsByTagName('form')[0];

The form constant is using the "Get Elements By Tag Name" method for all of the "Form" tags in the document. Since this returns an array of elements, the [0] is specifying the element at Index 0 of the array.

In this case, it is only saving the first array element as the Form constant. Depending on whatever other code there is, it could be used to quickly refer to the HTML form instead of running a document query each time you want to use it.

  • Related