javascript - 覆盖 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
然后运行测试的函数,但它不是很漂亮。
如果您有任何问题,请告诉我评论。
解决方案
重复评论中发生的事情;请,请,请不要尝试破解核心功能。如果您想创建一个自定义方法以在您的代码中使用,您可以扩展该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 中的原始方法。
有可能破解核心代码;但强烈建议不要尝试此操作。正如每个人都发现,当他们沿着这条路走下去时,通常会导致代码中出现意外错误——事情是相互关联的,而且不是立即知道的。
推荐阅读
- ios - iOS 使用 Agora 语音通话加入和离开频道时状态栏显示为红色
- php - 在php中进行求和时如何处理空值
- python - Runtime.ImportModuleError:无法导入模块“lambda_function”:没有名为“httplib2”的模块
- laravel - 如何在laravel中显示具有yajra数据表多对多关系的数据?
- hadoop - 为什么 cloudera 5.12 vm 中的默认复制因子为 1,而在以前的版本中为 3?
- swift - 向现有项目添加共享扩展。所以已经存在的项目 pod 开始出现错误
- python - 如何将字体标签设置为 Helvetica 并使用 matplotlib 重新设计轴标签文本
- openshift - VMware 上的 Openshift OKD 4.5
- javascript - 将数组数组附加到 FormData 并通过 AJAX 发送
- angular - 我们如何覆盖 angular2-query-builder 中的 getInputType 函数