Home > Article > Web Front-end > How to Select Elements with a Specific Attribute in IE7 and Earlier?
Native Alternative to querySelectorAll for Attribute Selection
Question:
How can you emulate the functionality of document.querySelectorAll('[data-foo]') without the availability of querySelectorAll() in IE7 or earlier?
Solution:
To address this compatibility issue, you can create a custom function, getAllElementsWithAttribute, that performs the necessary attribute selection using the native getElementsByTagName() method:
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) { matchingElements.push(allElements[i]); } } return matchingElements; }
By invoking this function with the desired attribute (e.g., getAllElementsWithAttribute('data-foo')), you can obtain an array of elements that possess the specified attribute.
The above is the detailed content of How to Select Elements with a Specific Attribute in IE7 and Earlier?. For more information, please follow other related articles on the PHP Chinese website!