2013-06-21

.getElementsByClassNameButOnlySometimes()

I'm making a paint application that involves SVG and Javascript. Now that IE actually supports it, SVG is a viable cross-browser method of implementing vector drawing, without having to rely on Raphaël*. Write once, run everywhere... ish.

I just spent a good ten minutes trying to figure out why I was getting the always-fun:

SCRIPT438: オブジェクトは 'getElementsByClassName' プロパティまたはメソッドをサポートしていません。

... error message. As it turns out, for once this was not davidiocy, it was Microsoft not bothering to implement something properly. In this case, selecting from the entire document works:

  
  document.getElementsByClassName("what")
  

... but selecting from an element lower down in the tree is impossible:

  
  document.getElementById("where").getElementsByClassName("what")
  

*sigh*

Well, thankfully there are people other than me who want to actually use SVG in a modern web page, and catch these little errors.

http://www.john-smith.me/incomplete-implementation-of-getelementsbyclassname-for-svg-in-ie9

To overcome this little issue, I've had to make my own method. I tried using the feature detection idea:

    
  if(!document.getElementsByClassName) {
    document.getElementsByClassName = function(className) {
      return this.querySelectorAll("." + className);
    };
    Element.prototype.getElementsByClassName = 
        document.getElementsByClassName;
  }
  

... but this does nothing - the method does actually exist, it just doesn't do what it is supposed to in IE. So we have to create a custom method:

  Element.prototype.getByClass = function (selector) {
    return this.querySelectorAll("." + selector);
  };

... and now it works.



The IE team has made significant progress in the browser in the last few versions, but stupid mistakes like this are just inexcusable. Either implement SVG fully - and I'm talking about animations here too, guys - or don't do it at all. This piecemeal stuff just makes you look like a bunch of incompetents, or worse, people who just don't care about the tech.



* which I love and admire, but is still as large as jQuery

No comments:

Post a Comment