'Not able to get the value of the input

I have a form with an input

<input type="text" class="class1 class2 class3 email" id="$email" name="$email" required="" value="[email protected]">

I am not able to get the value of the input. Am I missing something?

    val = document.getElementById('$email').value;
    val = document.getElementsByClassName("email").value;
    val = document.getElementsByName("$email").value;

TypeError: document.getElementById(...) is undefined



Solution 1:[1]

The following code will retrieve the value content of any element by its Id. See the last example for ByClassName.

https://jsfiddle.net/

<input type="text" class="class1 class2 class3 email" id="email" name="$email" required="" valu="[email protected]">

var element = document.getElementById("email");

if(element !== null) {
    console.log("Not null.");
  
  var content = element.value;
  console.log(content);
}
else {
    console.log("Null.");
}

ByClassName:

var element = document.getElementsByClassName("email");

if(element !== null) {
    console.log("Not null.");
  
  var content = element[0].value;
  console.log(content);
}
else {
    console.log("Null.");
}

Solution 2:[2]

getElementsByClassName and getElementsByName return HTMLCollection object. You need to access with index.

const val = [];
val[0] = document.getElementById('$email').value;
val[1] = document.getElementsByClassName("email")[0].value;
val[2] = document.getElementsByName("$email")[0].value;
console.log(val);
<input type="text" class="class1 class2 class3 email" id="$email" name="$email" required="" value="[email protected]">

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Jay
Solution 2