Code: hasAttribute for IE

Believe it or not, this actually works. Kind of.


  1. I can’t believe you actually posted that. It’s hilarious! And it does work… kind of.

  2. Yeah, hilarious … and broken ;P

    If the element doesn’t have the attribute but any of its children has??

    You can fix this by looking for indexOf(”>”) and comparing it to the one in the above example

  3. This is better:

    Element.Methods.Simulated.hasAttribute = function(element, attr) { return typeof element.attributes[attr] != “undefined”; };

  4. @Mislav: Damn. Good point.

    @Dean: Yeah, I was only about 50% serious with this one. Tobie and I were “in the shit” last night with a Prototype issue and after a while it became unclear how someElement.foo related to someElement.attributes.foo related to foo="bar" in the outerHTML. For a short period of time we were convinced that looking at the outerHTML gave you the best idea of which attributes were explicitly declared on an element.

    Tobie and I both have enough material on this subject to fill several ardent blog posts, so I’m sure you’ll hear more ranting on this topic.

  5. There you go.

  6. The “kind of” bit is that you will register a false positive if any of the elements descendants also has the attribute.

    I believe that if you want to make this work, you need something like (the code is probably buggy but you get the idea):

    Element.Methods.Simulated.hasAttribute = function(element, attr) { return element.outerHTML.match(/^<[^>]*>/)[0] .indexOf(” ” + attr + “=”) > -1; };

    The idea is that you want to test the indexOf against only the markup of the element itself. Then the kind of bit mostly goes away.

  7. Boy do I look dumb… this is what happens when you’re one of the first people to look at a post, go away and leave a comment the next day without refreshing the page.

    Nevertheless, if you really wanted to use outerHTML to do this sort of thing, you’d still want to do something like what I said.

Painfully Obvious was built with WordPress, Prototype, Slicehost, and other accoutrements. Colophon →