0

The following line of javascript gets a Uncaught TypeError: Object #Text has no method 'getAttribute' in chrome and safari but not in IE.

this.Element.getAttribute("whatever")

I get that this.Element is the main problem, but would like a temporary fix for debugging other parts of the code. How can test to see if a function is available on an item without getting a javascript error?

1
  • you could wrap it in a try/catch ? Commented Dec 3, 2012 at 18:15

2 Answers 2

3
if (this.Element.getAttribute)
{
// exists
}
else
{
// does not
}
Sign up to request clarification or add additional context in comments.

2 Comments

And what if this.Element.getAttribute is a boolean? Or anything other than a function?
@ScottSauyet look, all the OP wanted was to test if the .getattribute() existed for this object.This will work as long as this.Element is an object. And if a coder names a boolean as getAttribute, he shouldnt be coding :)
2
if (this && this.Element && typeof this.Element.getAttribute == "function") {
    // ...
}

2 Comments

See @Jaspers answer. checking if it is undefined would prevent you from having to check this and this.element
@Bot: No, instead if you skip these checks and Element was not defined, the JS engine would throw a TypeError, something like "Cannot read property 'getAttribute' of undefined

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.