Home > Web Front-end > JS Tutorial > 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
Release: 2024-10-30 20:33:02
Original
962 people have browsed it

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;
}
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template