【问题标题】:Document, HTMLDocument, Document, Element, Node, etc. What is their relationship?Document、HTMLDocument、Document、Element、Node等,它们的关系是什么?
【发布时间】:2020-02-29 09:05:49
【问题描述】:

我想知道documentHTMLDocumentDocumentElementNode 之间的关系以实现 IE8 的getElementsByClassName 方法.. 但每当我尝试这些方法时,它都不起作用:
document.getElementsByClassName = function(){}, HTMLDocument.getElementsByClassName=function(){}Element.prototype.getElementsByClassName=function(){}.

        if(!Element.getElementsByClassName) {
            Element.prototype.getElementsByClassName = function(arg){
                var cssSelector;
                var parentElement = this.document||this.documentElement.document||document;
                var queryElements = null;

                if(arg){
                    if(arg.indexOf(' ')>0){
                        cssSelector = '[class~="'+arg+'"]';
                    }else{
                        cssSelector = "."+arg;
                    }
                    queryElements = parentElement.querySelectorAll(cssSelector);
                }
                return queryElements;
            }
        }
        var elems = document.getElementsByClassName('limit').item(0);
        var triangles = elems.getElementsByClassName('triangle');
        debugger;

【问题讨论】:

  • 请定义“不工作”。控制台错误?
  • 我担心知道“它应该是怎样的”并不是你真正需要的......自从我使用 IE8 以来已经很长时间了,但是一些旧的浏览器实际上并没有像我们一样使用原型链现在习惯了,因此在创建实例后更改构造函数的原型并不会修改实例本身。但是你为什么要自己做呢?网上有很多这样的 polyfill 经过严格测试(顺便说一句,看看one of these,他们确实修改了实例,而不是原型)

标签: javascript internet-explorer dom bower


【解决方案1】:

您可以在this doc 中找到DocumentNodeElement 的描述,以及从here 中找到HTMLDocument 的描述。

  • Document 接口代表浏览器中加载的任何网页,并作为网页内容(即 DOM 树)的入口点。

  • Node 是一个接口,各种类型的 DOM API 对象都从该接口继承。

  • ElementNode 的一种。它只有各种元素共有的方法和属性。

  • HTMLDocument 接口扩展了 Window.HTMLDocument 属性以包含特定于 HTML 文档的方法和属性。

此外,如果您只想在 IE 8 中使用 getElementsByClassName 之类的东西,我认为最简单的方法是使用 document.querySelectorAll('.classname') 作为替代。有关此方法的更多信息,您可以参考this article

【讨论】:

  • “元素是最通用的基础......” 嗯,不。您可能在考虑 Node 吗?
  • 我从here得到了解释。
  • 那是错误的。 Document 中的所有对象都继承自 Node,而不是 Element。例如,在任何有效的 HTML5 文档中,document.firstChild 将是 <!DOCTYPE html> 节点,它不是元素。 (document.firstChild instanceof Element ==> false, document.firstChild instanceof DocumentType ==> true, document.firstChild instanceof Node ==> true)。所有#text 节点、所有属性节点等也是如此。注意 MDN 是由志愿者编写和维护的,不是官方的(即使质量一般)。
  • 我明白了,element 继承自 node 并且基于 node。元素是元素节点。我已经用你的代码进行了测试。完全正确。感谢您指出我的错误。
猜你喜欢
  • 1970-01-01
  • 2011-01-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-02-23
  • 1970-01-01
  • 2011-06-14
  • 2012-10-17
相关资源
最近更新 更多