Jan10

Code: hasAttribute for IE

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



302 Found

Found

The document has moved here.

7 Responses to “Code: hasAttribute for IE”

  1. 1 Tobie Langel Says:

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

  2. 2 Mislav Says:

    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. 3 Dean Edwards Says:

    This is better:


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

  4. 4 Andrew Says:

    @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. 5 Tobie Langel Says:

    There you go.

  6. 6 Adam van den Hoven Says:

    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. 7 Adam van den Hoven Says:

    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.


This is

The weblog of Andrew Dupont, web interface developer and writer.

Categories

Feeds

Feed Atom  Feed RSS

I wrote

Practical Prototype & script.aculo.us