Home > Web Front-end > JS Tutorial > body text

How to Select Elements by Attribute in Older Browsers?

DDD
Release: 2024-10-30 02:34:02
Original
993 people have browsed it

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

Example:

To retrieve elements with the "data-foo" attribute, you can use the following code:

<code class="javascript">const elementsWithFooAttribute = getAllElementsWithAttribute('data-foo');</code>
Copy after login

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!

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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!