"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to select elements by attributes when querySelectorAll is not available?

How to select elements by attributes when querySelectorAll is not available?

Posted on 2025-04-19
Browse:807

How to Select Elements by Attribute When querySelectorAll is Missing?

How to Retrieve Elements by Attribute When querySelectorAll is Unavailable

Despite its prevalence, the querySelectorAll method may not be universally accessible. For instance, older browsers like IE7 lack this functionality. However, it is possible to achieve similar results using a native approach that ensures compatibility with IE7.

Consider the following scenario:

Typically, one would utilize querySelectorAll to retrieve elements based on their attributes:

document.querySelectorAll('[data-foo]')

However, in the absence of querySelectorAll, an alternative solution is required.

To attain the same functionality natively, a JavaScript function can be constructed:

function getAllElementsWithAttribute(attribute) {
  var matchingElements = [];
  var allElements = document.getElementsByTagName('*');
  for (var i = 0, n = allElements.length; i 

This function traverses the entire document, retrieving all elements with a specific attribute. By invoking it:

getAllElementsWithAttribute('data-foo');

one can effectively retrieve elements with the "data-foo" attribute. This solution is both comprehensive and compatible with IE7, enabling access to elements by attribute even in browsers lacking querySelectorAll.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3