How to get the value of an attribute in Javascript

Tamara Caligari picture Tamara Caligari · Jun 17, 2016 · Viewed 68.6k times · Source

I have this input line which I am trying to extract the text of the value attribute:

    <input type="text" class="card-input small-font" 
ng-value="paymentVia.typeDisplay" readonly="" value="Credit card">

The function getAttribute("class") works fine and it returns card-input small-font but the function getAttribute("value") returns null. I tried .value as well but this returns an empty string.

Does anyone know why this is happening?

This is my JS:

function() {
   var x = document.getElementsByClassName("card-input small-font");
   var payment =x[18].value;

   return payment;
}

Answer

samayo picture samayo · Jun 17, 2016

Node values and Element Attributes are different parts of an html tag. So, you have to use element.value instead.

This is a an example, to show you how you can fetch value, data, attribute from an input field.

The HTML input field.

<input type="text" id="profile" data-nationality="Eritrean" value="Simon">

and the javascript.

var el = document.getElementById("user-profile"); 

console.log(el.value) // Simon
console.log(el.getAttribute("id")) // profile
console.log(el.dataset.nationality) // Eritrean