getElementsByClassName()在IE6,IE7,IE8等旧的Internet Explorer中不起作用 [英] getElementsByClassName() doesn't work in old Internet Explorers like IE6, IE7, IE8

本文介绍了getElementsByClassName()在IE6,IE7,IE8等旧的Internet Explorer中不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码:

var borderTds = document.getElementsByClassName('leftborder');

在Internet Explorer 6,7和8中给我一条错误消息:

gives me an error message in Internet Explorer 6, 7 and 8:


对象不支持此方法

Object does not support this method

如何选择元素他们在这些浏览器中的类?

How can I select elements by their class in these browsers?

我不想使用JQuery。

I prefer not to use JQuery.

推荐答案

解决方案可能有所帮助。这是一个在纯javascript中实现的自定义 getElementsByClassName 函数,可以在IE中运行。

This solution may help. This is a custom getElementsByClassName function implemented in pure javascript, that works in IE.

基本上这个脚本在做什么正在逐一探讨所有可能的选择并挑选最好的选择。这些选项包括:

Essentially what this script is doing is probing, one by one, all possible options and picks the best one available. These options are:


  1. 原生 document.getElementsByClassName 功能。

  2. document.evaluate function,它允许评估XPath查询。

  3. 遍历DOM树。

  1. Native document.getElementsByClassName function.
  2. document.evaluate function, which allows evaluation of XPath queries.
  3. Traversing the DOM tree.

当然第一个是性能最佳的,但后者应该可以在任何地方使用,包括IE 6。

Of course the first one is the best performance-wise, however the latter should be available everywhere including IE 6.

页面上也提供的用法示例如下所示:

Usage example, which is also available on the page, looks like this:

getElementsByClassName("col", "div", document.getElementById("container")); 

因此该函数允许3个参数:class(必需),标签名称(可选,搜索所有标签)如果没有指定),根元素(可选,文档,如果没有指定)。

So the function allows 3 parameters: class (required), tag name (optional, searches for all tags if not specified), root element (optional, document if not specified).

更新。博客帖子中链接的解决方案托管在Google代码将于2016年1月关闭。但是,作者已将其提供给 GitHub 。感谢 flodin 在评论中指出这一点。

Update. The solution linked in the blog post is hosted on the Google Code which is shutting down in Jan 2016. However the author has made it available on GitHub. Kudos to flodin pointing this out in the comments.

这篇关于getElementsByClassName()在IE6,IE7,IE8等旧的Internet Explorer中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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