Polyfill for getElementsByClassName for particular

2020-02-12 11:08发布

问题:


Want to improve this question? Update the question so it's on-topic for Stack Overflow.

Closed 6 years ago.

How can I make this.getElementsByClassName('class')[0] work for Internet Explorer 6-8? Is there any polyfill to fix this?

回答1:

Just for the record, older browsers are still alive because people keep making efforts to support them.

Polyfill for document.getElementsByClassName

With that said, a short google search could have brought you to this link: https://gist.github.com/eikes/2299607

The polyfill for IE6/7 is like this:

if (d.evaluate) { // IE6, IE7
  pattern = ".//*[contains(concat(' ', @class, ' '), ' " + search + " ')]";
  elements = d.evaluate(pattern, d, null, 0, null);
  while ((i = elements.iterateNext())) {
    results.push(i);
  }
}

Based on the document.evaluate method

https://developer.mozilla.org/en-US/docs/Web/API/document.evaluate

EDIT: Polyfill for element.getElementsByClassName

You seem to want to call the getElementsByClassName method on a HTML element instead of on the document. Unfortunately i don't think you can polyfill that on IE6 and 7 (and even 8), as this answer seems to suggest: How to add my own methods to HTMLElement object?

You can still use document.evaluate to acomplish the functionality you want (hint: the second parameter is a context node; it should be your element), but you need to change the calling code to something like this:

<div onclick="myPolyfill('class', this)[0].innerHTML = 'works'">