首页 > 解决方案 > 覆盖 HTML DOM 元素方法 JS

问题描述

简短的问题:

如何在JS中覆盖DOM 内置函数document.getElementById ()或构建自己的 方法?


说明:

我正在开发一个 API,它使用属性来定位我的 HTML 页面中的 div。

我可以使用此方法获取 div 的属性:

for (var att, i = 0, atts = div.attributes, n = atts.length; i < n; i++) {
    att = atts[i];
    nodeName = att.nodeName; 
    nodeValue = att.nodeValue;
}

然后,我需要使用这段代码来检查给定 HTML 对象的属性。我构建了一个方法来检查文档的 div 属性

document.getElementByIdentifier = function (identifier) {
    for (var i = 0; i < this.children.length; i++) {
         for (var att, i = 0, atts = div.attributes, n = atts.length; i < n; i++) {
            att = atts[i];
            nodeName = att.nodeName; 
            nodeValue = att.nodeValue;
            // Here I check the attributes
        }
    }
} 

但是,我不能HTML Dom 对象(此处的document对象除外)调用此函数。我没有找到如何用document的东西allHTMLElements。目标是拥有与示例相同的使用自由document.getElementById

我该怎么做?


注意:我很惊讶,因为document.getElementById似乎位于document对象中。但是,当我尝试将自己的方法构建到此对象中时,它不起作用。为什么?


其他注意事项:这是(至少对我而言)一个HTML DOM 对象var A = document.getElementById ("C");。这里的对象 A 是一个 HTML Dom 对象调用:当我尝试时 google chrome 的“object” console.log (typeof A);


否则请注意:

这是我的一个 div 的示例:

<script identifier="OAdgRzf"></script>

最后注意

使用document.querySelector是我已经在我的图书馆使用的方式。但是,我现在必须对用户调用的元素运行更新和测试。我构建了一个使用document.querySelector然后运行测试的函数,但它不是很漂亮。


如果您有任何问题,请告诉我评论。

标签: javascriptdom

解决方案


重复评论中发生的事情;请,请,不要尝试破解核心功能。如果您想创建一个自定义方法以在您的代码中使用,您可以扩展该Object对象...

Object.prototype.getEl = function( selector ){
	return document.querySelector( `[special-attribute="${selector
}"]` );
}
console.log( document.getEl('potatoSalad') );
<div special-attribute="potatoSalad">one two three</div>

通过这种方式,您可以进行更简洁的调用document.getEl()来定位您想要的元素,同时仍然保留 JavaScript 中的原始方法。

有可能破解核心代码;但强烈建议不要尝试此操作。正如每个人都发现,当他们沿着这条路走下去时,通常会导致代码中出现意外错误——事情是相互关联的,而且不是立即知道的。


推荐阅读