0

I have an ajax 'POST' method that sends the id input to a php file. For some reason whenever I write input.value method, it returns undefined:

input = document.getElementsByClassName("Input");
const id = input.value;
alert(id);

What am I doing wrong?

Edit: I tried making the element as a separate id instead of a class and the problem disappeared.

  • It would be helpful if you could provide more context but try if this is working for you `document.getElementsByClassName("Input")[0]` since getElementsByClassName normally returns an array. – Smlok Jun 23 '20 at 09:41
  • Duplicate of [What do querySelectorAll and getElementsBy\* methods return?](https://stackoverflow.com/questions/10693845/what-do-queryselectorall-and-getelementsby-methods-return) – Guy Incognito Jun 23 '20 at 09:46

1 Answers1

1

getElementsByClassName() returns an array-like collection of elements, not a single element.

You'll need to extract one of the elements from the collection, e.g.

input = document.getElementsByClassName("Input");
const id = input[0].value; //<--
alert(id);

Better would be to target the exact element in some way e.g.

document.querySelector('#theActualElement'); //<-- returns single element
Mitya
  • 33,629
  • 9
  • 60
  • 107
  • Hey, thanks for the response. For some reason I am getting an empty string instead of a value inputted :\ –  Jun 24 '20 at 06:50
  • Well then something outside the scope of the question is responsible. Either you do not have elements with class `.Input` or they are not being found (you may be running this code before the elements are present in the DOM). Try to set up a [minimal, verifiable, reproducible example](https://stackoverflow.com/help/minimal-reproducible-example). – Mitya Jun 24 '20 at 09:56
  • Thanks for the help, I tried making the element as a separate id instead of a class and the problem disappeared. –  Jun 24 '20 at 16:28