Search code examples
javascripthtmlinputgetelementbyidautofill

Fill in a input field on a website with JavaScript if it has no id?


How can I fill in a input field on a website with JavaScript if it has no id? Example:

<input type="text" placeholder="First Name" value="" class="someclass">
<input type="text" placeholder="Last Name" value="" class="someclass">

I only want to fill in the first input field.

If it had an ID I could just do document.getElementById... the class and type are used by several input fields on the website. Could I maybe use the placeholder somehow?


Solution

  • Simply select it with document.querySelector('input.someclass')

    EDIT

    If the order and amount of inputs is always the same on your website just do this:

    const inputs = document.querySelectorAll('input')
    

    You can choose the input from the array that querySelectorAll returns or loop through the array to input the values.

    const inputs = document.querySelectorAll('input');
    const valuesToInput = [1,2,3,4,5,6,7,8,9];
    for(let i = 0; i < inputs.length; i += 1) {
       inputs[i].value = valuesToInput[i];
    }