admin 管理员组文章数量: 1087132
Why do I get undefined
as result of console.log(tes_val)
? 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">
Why do I get undefined
as result of console.log(tes_val)
? 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.
Share Improve this question edited Mar 9, 2017 at 10:21 gyre 16.8k4 gold badges40 silver badges47 bronze badges asked Mar 9, 2017 at 8:59 Mr. MikeMr. Mike 4536 silver badges23 bronze badges 2-
5
Because
tes
is a collection. Usevar tes_val = tes[0].value;
. – dfsq Commented Mar 9, 2017 at 9:00 - getElementsByClassName returns a collection like an array. If there is only one element with that class name you can use tes[0].value – BenShelton Commented Mar 9, 2017 at 9:02
4 Answers
Reset to default 6getElementsByClassName
returns an HTMLCollection, so in order to access first found element in this collection you need to use [0]
index:
var tes_val = tes[0].value;
However, this is clumsy way to use API. If you are only interested in the first element with class a_b_1
use Document.querySelector method:
var tes = document.querySelector('.a_b_1');
var tes_val = tes.value;
console.log(tes_val);
getElementsByClassName(...)
returns a list of elements. Note the plural s
in the name of the method! Use getElementsByClassName(...)[0]
to access the first element in the list.
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.
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);
DEMO
var tes = $('.a_b_1');
var tes_val = tes.val();
console.log(tes_val);
<script src="https://ajax.googleapis./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
本文标签: javascriptWhy do I get undefined when using documentgetElementsByClassName()valueStack Overflow
版权声明:本文标题:javascript - Why do I get `undefined` when using `document.getElementsByClassName(...).value`? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://roclinux.cn/p/1744030208a2521356.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论