Code: hasAttribute for IE
Believe it or not, this actually works. Kind of.
Element.Methods.Simulated.hasAttribute = function(element, attr) {
return element.outerHTML.match(/^<[^>]*>/)[0].indexOf(" " + attr + "=") > -1;
};
Believe it or not, this actually works. Kind of.
Element.Methods.Simulated.hasAttribute = function(element, attr) {
return element.outerHTML.match(/^<[^>]*>/)[0].indexOf(" " + attr + "=") > -1;
};
Comments
I can’t believe you actually posted that. It’s hilarious! And it does work… kind of.
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
This is better:
Element.Methods.Simulated.hasAttribute = function(element, attr) {
return typeof element.attributes[attr] != "undefined";
};
@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 tosomeElement.attributes.foo
related tofoo="bar"
in theouterHTML
. For a short period of time we were convinced that looking at theouterHTML
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.
There you go.
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.
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.