sisaln
sisaln

Reputation: 220

Uncaught TypeError: Cannot set property 'value' of undefined for input fields

I have this code:

var username = 'xyz';
var password = 'xyz';
var input = document.getElementsByClassName('_2hvTZ pexuQ zyHYP');
var button = document.getElementsByClassName('sqdOP L3NKy y3zKF');
input[0].value = username;
input[1].value = password;
button.click();

Every time I get this error, but in the console, the two input fields are found in the dom.

Uncaught TypeError: Cannot set property 'value' of undefined

I'm able to get the HTML collection array of the two elements.

This is the outerHTML of them:

<input aria-label="Password" aria-required="true" autocapitalize="off" autocorrect="off" name="password" type="password" class="_2hvTZ pexuQ zyHYP" value=""> 

<input aria-label="Numero di telefono, nome utente o e-mail" aria-required="true" autocapitalize="off" autocorrect="off" maxlength="75" name="username" type="text" class="_2hvTZ pexuQ zyHYP" value="">" 

Here is a screen of the consolle consolle screen

Any solution?

Upvotes: 1

Views: 1057

Answers (2)

connexo
connexo

Reputation: 56754

A class name cannot contain spaces. If you are looking for elements with each of those space-separated classes, use querySelectorAll instead of getElementsByClassName:

const input = document.querySelectorAll('._2hvTZ.pexuQ.zyHYP');
const button = document.querySelectorAll('.sqdOP.L3NKy.y3zKF');

As mentioned before, since button will be an array-like NodeList, which has no click() method.

Here's an example with the HTML you added in the comments:

const input = document.querySelectorAll('._2hvTZ.pexuQ.zyHYP');

console.log(input.length); // let's see how many there are
input[0].value = "I'm here";
input[1].value = "and here";
<input aria-label="Password" aria-required="true" autocapitalize="off" autocorrect="off" name="password" type="password" class="_2hvTZ pexuQ zyHYP" value="">
<input aria-label="Numero di telefono, nome utente o e-mail" aria-required="true" autocapitalize="off" autocorrect="off" maxlength="75" name="username" type="text" class="_2hvTZ pexuQ zyHYP" value="">

Upvotes: 2

Rick
Rick

Reputation: 1870

For this I would think you would want to access the fields by id, not class. that's not good programming, what you have.

also, you should always check if your array contains at least 2 elements before trying to access the second element of it.

one more thing... isn't "button" an array? (which is a bad name for an array) not sure if button.click() makes any sense.

Upvotes: -1

Related Questions