有人可以告诉我如何写函数: getElementsWithAttributeName("attr-name")
?
它应返回包含属性attr-name
的当前document
的所有元素。
另外,如何将此功能添加到文档?
任何响应都将不胜感激。
您可以在document
中添加一种方法:
document.fnName = function(args){ ... };
正如Rob W在评论中指出的那样,您可以使用现有的document.querySelectorAll()
方法并通过CSS选择器。如果您真的想要像getElementsByAttributeName("attr-name")
一样工作,可以做到这一点:
document.getElementsByAttributeName = function(attrName){
return document.querySelectorAll('[' + attrName+']');
};
注意,这仅是IE8 。( document.querySelectorAll()
需要CSS3选择器IE9。)
参考:
- mdn:
querySelectorAll()
docs - CSS-tricks:CSS属性上的瘦