javascript 按类而不是 Id 获取元素

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

Get Element by Class instead of Id

javascriptcssclasshtml

提问by GreatestSwordsman

I have a button called WatchMode.

我有一个名为 WatchMode 的按钮。

When you click this button, it will close certain divs, specified by the div ID.

当您单击此按钮时,它将关闭由 div ID 指定的某些 div。

The javascript for this is as follows:

用于此的 javascript 如下:

function watchmode() { 
document.getElementById('aps30').innerHTML = " ";
} 

Now, I want to do the same for a div that appears twice on my page, this div has a Class instead of an ID.

现在,我想对在我的页面上出现两次的 div 做同样的事情,这个 div 有一个类而不是一个 ID。

I tried adding this line to the javascript, but it doesn't seem to work

我尝试将此行添加到 javascript,但它似乎不起作用

document.getElementByClassName('floater').innerHTML = " ";

Any suggestions ??

有什么建议 ??

回答by jfriend00

You have to change a number of things:

你必须改变一些事情:

  1. Fix the spelling mistake in getElementsByClassName
  2. Treat the return results of that function call as an array
  3. Loop through the contents of the returned array in order to operate on the results
  4. Understand that not all old browsers (no version of IE before IE9) support this function so if you want to target older browsers, you may have to check for its existence and use a substitute implementation if it isn't natively available. You can see the browser support hereand see the alternate implementations in the link in Justin's answer.
  1. 修复 getElementsByClassName 中的拼写错误
  2. 将该函数调用的返回结果视为数组
  3. 循环遍历返回数组的内容以对结果进行操作
  4. 了解并非所有旧浏览器(IE9 之前没有 IE 版本)都支持此功能,因此如果您想针对旧浏览器,您可能需要检查它是否存在并使用替代实现(如果它不是本机可用的)。您可以在此处查看浏览器支持并在 Justin 的回答中的链接中查看替代实现。

Here's the code:

这是代码:

var divs = document.getElementsByClassName('floater');
for (var i = 0; i < divs.length; i++) {
    divs[i].innerHTML = " ";
}

This is a place where jQuery is really useful. In jQuery, it would just be:

这是 jQuery 真正有用的地方。在 jQuery 中,它只是:

$(".floater").html(" ");

That would automatically find all objects with that class and set the innerHTML of all matching objects to your string.

这将自动查找具有该类的所有对象,并将所有匹配对象的 innerHTML 设置为您的字符串。

回答by BumbleShrimp

First, I am not sure whether this was a typo or not, but you put:

首先,我不确定这是否是一个错字,但是您输入了:

document.get**Element**ByClassName('floater').innerHTML = " ";

The command is actually:

命令实际上是:

document.get**Elements**ByClassName();

notice elements is plural.

通知元素是复数。

Now, this doesn't behave the same as getElementById. It returns a nodelist, or in other words a list of all the elements with the specified class.

现在,这与 getElementById 的行为不同。它返回一个节点列表,或者换句话说,一个包含指定类的所有元素的列表。

You can store the results in an array like so:

您可以将结果存储在一个数组中,如下所示:

var array_name = document.getElementsByClassName('floater');

and then loop through the results to perform your actions:

然后遍历结果以执行您的操作:

for ( var i=0, var len=array_name.length; i<len; ++i ){
    array_name[i].innerHtml = 'text';
}

I have not tested the code that I wrote out here, but the method is tried and true.

我没有测试我在这里写的代码,但该方法已经过验证。

[edit] I forgot to mention that this function is not supported by IE, and you can accomplish this using jQuery by doing something like: $('floater').html('text'); and it is cross-browser. You can also search the web for something that emulates the behavior of getElementsByClassName and works in all browsers.

[编辑] 我忘了提到 IE 不支持此功能,您可以使用 jQuery 通过执行以下操作来完成此操作: $('floater').html('text'); 它是跨浏览器的。您还可以在网络上搜索模拟 getElementsByClassName 行为并在所有浏览器中工作的内容。

Here is an article with a better function that emulates getElementsByClassName:

这是一篇模拟 getElementsByClassName 的具有更好功能的文章:

http://www.webmuse.co.uk/blog/custom-getelementsbyclassname-function-for-all-browsers/

http://www.webmuse.co.uk/blog/custom-getelementsbyclassname-function-for-all-browsers/

document.getElementsByClassName = function( classname ) {
    var elArray = [];
    var tmp = document.getElementsByTagName("*");
    var regex = new RegExp("(^|\s)" + classname + "(\s|$)");
    for ( var i = 0; i &lt; tmp.length; i++ ) {

        if ( regex.test(tmp[i].className) ) {
            elArray.push(tmp[i]);
        }
    }

    return elArray;
;

This works very well, is cross browser compatible, and is used the same way as getElementsByClassName.

这非常有效,跨浏览器兼容,并且与 getElementsByClassName 的使用方式相同。

usage example from the article: var el = document.getElementsByClassName("para");

文章中的用法示例: var el = document.getElementsByClassName("para");

    for ( var i = 0; i &lt; el.length; i++ ) {
        el[i].style.color = "red";
    }

回答by Justin Beckwith

The easiest way to do this is to use jQuery. Here is a post that should answer your question:

最简单的方法是使用 jQuery。这是一个应该回答你的问题的帖子:

How to getElementByClass instead of GetElementById with Javascript?

如何使用 Javascript getElementByClass 而不是 GetElementById?

回答by Josh Leitzel

Your function name has a spelling mistake — it should be getElementsByClassName(note the plural, elements, not element):

你的函数名有一个拼写错误——它应该是getElementsByClassName(注意复数,元素,而不是元素):

document.getElementsByClassName('floater').innerHTML = " ";