Home  >  Article  >  Web Front-end  >  How to Select Elements with a Specific Attribute in IE7 and Earlier?

How to Select Elements with a Specific Attribute in IE7 and Earlier?

Barbara Streisand
Barbara StreisandOriginal
2024-10-30 20:33:02842browse

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn