4

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

dakab
  • 5,379
  • 9
  • 43
  • 67
user2799274
  • 133
  • 1
  • 1
  • 9

1 Answers1

5

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'">
Community
  • 1
  • 1
Tibos
  • 27,507
  • 4
  • 50
  • 64
  • You are right, I would not support IE6 and IE7 but at work asked me to do it. Anyhow it does not work. Try this: http://pastebin.com/PkGSgXMx – user2799274 Sep 22 '13 at 14:19
  • Unfortunately i am unable to test on IE6 in any way and in IE7 at the moment. You can try to take it apart and see exactly what doesn't work (is it the document.evaluate method?, is anything else?, etc). Good luck! PS: If you're very desperate you can always just iterate over all the nodes and check their classname property. Hopefully that method is not so critical that a horribly unoptimized solution will slow down your whole site. – Tibos Sep 22 '13 at 14:33
  • It is very true, I work with people who are incapable. Here a screen after click http://oi39.tinypic.com/5tyzao.jpg (in english: Object does not support the property or method 'getElementByClassName'). – user2799274 Sep 22 '13 at 14:42
  • Uhh, right. The problem is that the code above defines the document.getElementByClassName method and you actually want one for the element. Unfortunately i don't think you can do that. I will edit my answer to make it clear. – Tibos Sep 22 '13 at 14:50
  • At the end I am using querySelector which is also supported by IE8, on IE7-IE8 I will leave only the features vital as you have advised me. Thank you. – user2799274 Sep 22 '13 at 15:18
  • +1 for "older browsers are still alive because..." line. – rvighne Jan 24 '14 at 03:18