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. Use var 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
Add a ment  | 

4 Answers 4

Reset to default 6

getElementsByClassName 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