您可以编写一个运行getElementsByTagName(’*’)的函数,并仅返回具有“ data-foo”属性的那些元素:
function getAllElementsWithAttribute(attribute){ var matchingElements = []; var allElements = document.getElementsByTagName('*'); for (var i = 0, n = allElements.length; i < n; i++) { if (allElements[i].getAttribute(attribute) !== null) { // Element exists with attribute. Add to array. matchingElements.push(allElements[i]); } } return matchingElements;}然后,
getAllElementsWithAttribute('data-foo');


