Home > Article > Web Front-end > How to Retrieve Elements by Attributes in Pre-querySelectorAll Browsers?
Browsers prior to IE9 lack the powerful querySelectorAll() method, posing a challenge when you need to retrieve elements based on specific attributes. To address this, let's explore a native solution that works in IE7 and higher.
We can simulate the functionality of querySelectorAll by leveraging the getElementsByTagName method. Let's create a function called getAllElementsWithAttribute to find elements with a particular attribute:
<code class="js">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 has the attribute. Add it to the array. matchingElements.push(allElements[i]); } } return matchingElements; }</code>
This function takes an attribute name as an argument and iterates through all elements in the document. For each element, it checks if the specified attribute exists and is not null. If so, the element is added to an array of matching elements.
To retrieve all elements with the data-foo attribute, simply call:
<code class="js">getAllElementsWithAttribute('data-foo');</code>
This approach provides a native solution for retrieving elements by attributes in browsers lacking querySelectorAll, ensuring compatibility with IE7 and higher.
The above is the detailed content of How to Retrieve Elements by Attributes in Pre-querySelectorAll Browsers?. For more information, please follow other related articles on the PHP Chinese website!