[英]Why do I get `undefined` when using `document.getElementsByClassName(…).value`?
Why do I get undefined
as result of console.log(tes_val)
? 为什么由于
console.log(tes_val)
导致undefined
? How can I fix it? 我该如何解决?
var tes = document.getElementsByClassName('a_b_1'); var tes_val = tes.value; console.log(tes_val);
<input type="hidden" class="a_b_1" name="c_d_1" value="1|2|3">
Thank you. 谢谢。
getElementsByClassName
returns an HTMLCollection , so in order to access first found element in this collection you need to use [0]
index: getElementsByClassName
返回一个HTMLCollection ,因此,为了访问此集合中的第一个找到的元素,您需要使用[0]
索引:
var tes_val = tes[0].value;
However, this is clumsy way to use API. 但是,这是使用API的笨拙方式。 If you are only interested in the first element with class
a_b_1
use Document.querySelector method: 如果仅对类
a_b_1
的第一个元素感兴趣, a_b_1
使用Document.querySelector方法:
var tes = document.querySelector('.a_b_1');
var tes_val = tes.value;
console.log(tes_val);
getElementsByClassName(...)
returns a list of elements. getElementsByClassName(...)
返回元素列表。 Note the plural s
in the name of the method! 注意方法名称中的复数
s
! Use getElementsByClassName(...)[0]
to access the first element in the list. 使用
getElementsByClassName(...)[0]
访问列表中的第一个元素。
var tes = document.getElementsByClassName('a_b_1')[0] var tes_val = tes.value console.log(tes_val) //=> "1|2|3"
<input type="hidden" class="a_b_1" name="c_d_1" value="1|2|3">
document.getElementsByClassName array-like object of all child elements. 所有子元素的document.getElementsByClassName类数组对象。
So you have to select the specific element by passing the index 因此,您必须通过传递索引来选择特定元素
var tes = document.getElementsByClassName('a_b_1');
var tes_val = tes[0].value;
console.log(tes_val);
var tes = $('.a_b_1'); var tes_val = tes.val(); console.log(tes_val);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type="hidden" class="a_b_1" name="c_d_1" value="1|2|3">
Use .val()
for jquery 使用
.val()
进行jquery
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.