Javascript 如何使用javascript通过类名获取值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34207638/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 16:03:19  来源:igfitidea点击:

how to get value by class name using javascript

javascript

提问by Songs

Sorry, it's basic one but I trying to search on google anyways but still not get success.

对不起,这是基本的,但我无论如何都试图在谷歌上搜索,但仍然没有成功。

I want get value of this

我想得到这个价值

<input type='hidden' class='hid_id' value='1' />

Using JavascriptI want alert value 1

使用 Javascript我想要警报值1

I trying this

我试试这个

var id = document.getElementsByClassName("hid_id");
alert (id);

But it's alert [object HTMLInputElement]

但它很警觉 [object HTMLInputElement]

please help me now.

请现在帮助我。

回答by Keammoort

getElementsByClassName() returns an array so you have to access first element (if there is any). Then try accessing value property:

getElementsByClassName() 返回一个数组,因此您必须访问第一个元素(如果有)。然后尝试访问 value 属性:

var id = document.getElementsByClassName("hid_id");
if (id.length > 0) {
    alert (id[0].value);
}

jsfiddle

提琴手

回答by madox2

try this:

尝试这个:

var id = document.getElementsByClassName("hid_id")[0].value;

回答by Josh Crozier

The method .getElementsByClassName()returns an array-like object of elements.

方法.getElementsByClassName()返回一个类似数组的元素对象。

You need to access an element in the object rather than the object itself (which is why you were seeing [object HTMLInputElement]).

您需要访问对象中的元素而不是对象本身(这就是您看到 的原因[object HTMLInputElement])。

For instance, the first object's valueproperty:

例如,第一个对象的value属性:

var elements = document.getElementsByClassName("hid_id");
var value = elements[0].value;

alert(value); // 1

Alternatively, you could also use the .querySelector()method:

或者,您也可以使用以下.querySelector()方法

var value = document.querySelector('.hid_id').value;
alert(value); // 1