Home > Article > Web Front-end > How to Select Elements by Attribute in Older Browsers?
Question:
How can you retrieve elements by a specific attribute when the querySelectorAll method is unavailable, such as in older browsers like IE7?
Native Solution:
In browsers that lack querySelectorAll, you can implement a custom function to achieve similar functionality:
<code class="javascript">function getAllElementsWithAttribute(attribute) { const matchingElements = []; const allElements = document.getElementsByTagName('*'); for (let i = 0; i < allElements.length; i++) { if (allElements[i].getAttribute(attribute) !== null) { // Element exists with attribute. Add to array. matchingElements.push(allElements[i]); } } return matchingElements; }</code>
Example:
To retrieve elements with the "data-foo" attribute, you can use the following code:
<code class="javascript">const elementsWithFooAttribute = getAllElementsWithAttribute('data-foo');</code>
The above is the detailed content of How to Select Elements by Attribute in Older Browsers?. For more information, please follow other related articles on the PHP Chinese website!