javascript 如何按类而不是“GetElementById”获取元素?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16739969/
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-10-27 05:48:28  来源:igfitidea点击:

How can i get elements by class instead of "GetElementById"?

javascriptgetelementbyidgetelementsbyclassname

提问by Fábio Pavani

So, this is the code:

所以,这是代码:

<a id="link" href="https://url.com/">URL:</a>
<input id="value"/>

<script type="text/javascript">
    var link= document.getElementById('link');
    var input= document.getElementById('value');
    input.onchange=input.onkeyup= function() {
        link.search= 'extendurl/'+encodeURIComponent(input.value);
    };
</script>

this is working, but i need to use the class instead of the ID. I try this:

这是有效的,但我需要使用类而不是 ID。我试试这个:

<script type="text/javascript">
    var link= document.getElementByClassName("link")[0];
    var input= document.getElementByClassName("value")[0];
    input.onchange=input.onkeyup= function() {
        link.search= 'extendurl/'+encodeURIComponent(input.value);
        link.firstChild.data= link.href;
    };
</script>

<a class="link" href="https://url.com/">URL:</a>
<input class="value"/>

i don't know why, but this isn't working.

我不知道为什么,但这不起作用。

Someone?

有人吗?

回答by Denys Séguret

The precise name is important.

准确的名称很重要。

Change

改变

getElementByClassName

to

getElementsByClassName

There's a sbecause there might be more than one element with a give class, contrary to elements with a specific id.

有一个是s因为可能有多个元素具有一个给定类,与具有特定 id 的元素相反。

回答by scrblnrd3

There can be many elements with the exact same class names, so you have to adjust it for that

可以有许多具有完全相同类名的元素,因此您必须为此进行调整

instead of

代替

getElementByClassName

you have to do

你必须做

getElementsbyClassName("someclass");

and it will return an array of all of them

它将返回所有这些的数组