如何在Javascript中获取属性的值 [英] How to get the value of an attribute in Javascript
问题描述
我有此输入行,我正在尝试提取value属性的文本:
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">
函数getAttribute("class")
正常工作,它返回card-input small-font
,但是函数getAttribute("value")
返回null
.我也尝试过.value,但这会返回一个空字符串.
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?
这是我的JS:
function() {
var x = document.getElementsByClassName("card-input small-font");
var payment =x[18].value;
return payment;
}
推荐答案
元素属性是html标记的不同部分.
因此,您必须改为使用element.value
.
Node values and Element Attributes are different parts of an html tag.
So, you have to use element.value
instead.
这是一个示例,向您展示如何从输入字段中获取value
,data
,attribute
.
This is a an example, to show you how you can fetch value
, data
, attribute
from an input field.
HTML输入字段.
The HTML input field.
<input type="text" id="profile" data-nationality="Eritrean" value="Simon">
和javascript.
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
这篇关于如何在Javascript中获取属性的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!