Javascript 如何编写类似“document.getElementsWithAttributeName”(“attr name”)这样的函数?

Javascript 如何编写类似“document.getElementsWithAttributeName”(“attr name”)这样的函数?,javascript,html,dom,Javascript,Html,Dom,有人能告诉我如何编写函数:getElementsWithAttributeName(“attr name”) 它应该返回当前文档中包含属性attr name的所有元素 另外,如何将此函数添加到文档中 任何回复都将不胜感激。您可以向文档添加一个方法,如下所示: document.fnName = function(args){ ... }; 正如Rob W在评论中指出的那样,您只需使用现有的document.queryselectoral()方法并传递css选择器。如果您真的希望它像getEle

有人能告诉我如何编写函数:
getElementsWithAttributeName(“attr name”)

它应该返回当前
文档中包含属性
attr name
的所有元素

另外,如何将此函数添加到文档中


任何回复都将不胜感激。

您可以向
文档添加一个方法,如下所示:

document.fnName = function(args){ ... };

正如Rob W在评论中指出的那样,您只需使用现有的
document.queryselectoral()
方法并传递css选择器。如果您真的希望它像
getElementsByAttributeName(“attr name”)
那样工作,您可以这样做:

document.getElementsByAttributeName = function(attrName){
    return document.querySelectorAll('[' + attrName+']'); 
};

注意,这只是IE8+版本。(
document.queryselectoral()
但是CSS3选择器需要IE9。)

参考资料


document.querySelectorAll(“[attr name]”)
@RobW你为什么要发表评论?你不能直接回答到目前为止你都做了些什么?你的代码有什么问题?document.getElementsByAttribute=Element.prototype.getElementsByAttribute=function(attr){var nodeList=this.getElementsByTagName('*');var noderray=[];for(var i=0,node;node=nodeList[i];i++{if(node.getAttribute(attr))noderray.push(node);}返回noderray;}@感谢您的编辑-愚蠢的错误;-)非常感谢。这符合我的目的。