Home  >  Article  >  Web Front-end  >  How to Select Elements by Attribute in Older Browsers?

How to Select Elements by Attribute in Older Browsers?

DDD
DDDOriginal
2024-10-30 02:34:021073browse

How to Select Elements by Attribute in Older Browsers?

How to Retrieve Elements by Attribute Without querySelectorAll

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!

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