按类而不是Id获取元素 [英] Get Element by Class instead of Id

查看:131
本文介绍了按类而不是Id获取元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为WatchMode的按钮。

I have a button called WatchMode.

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

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

这样的javascript如下:

The javascript for this is as follows:

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

现在,我想做一个div,页面,这个div有一个类而不是一个ID。

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.

我试图将这一行添加到javascript,但似乎不起作用

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

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

任何建议

推荐答案

您必须更改多项内容:


  1. 修复getElementsByClassName中的拼写错误

  2. 将该函数调用的返回结果作为数组处理

  3. 循环返回数组的内容,以对结果进行操作

  4. 了解并非所有旧浏览器(IE9之前没有IE版本)支持此功能,因此如果要定位旧版本的浏览器,则可能必须检查其是否存在,如果不是本机可用的,可以使用替代实现。您可以在此处查看浏览器支持,并在Justin的回答中查看链接中的替代实现。

  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 here and see the alternate implementations in the link in Justin's answer.

这是代码:

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

这是jQuery非常有用的地方。在jQuery中,它将是:

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

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

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

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

这篇关于按类而不是Id获取元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆