Code Snippet

Home » Code Snippets » JavaScript » Test if Element Supports Attribute

Test if Element Supports Attribute

Not all browsers support all attributes on all elements. There are a number of new attributes in HTML5, so the idea of testing to see what kind of browser environment you are in becomes every increasingly important.

function elementSupportsAttribute(element, attribute) {
  var test = document.createElement(element);
  if (attribute in test) {
    return true;
  } else {
    return false;
  }
};

Usage

if (elementSupportsAttribute("textarea", "placeholder") {

} else {
   // fallback
}

Subscribe to The Thread

  1. “(” –> “)”


    if (elementSupportsAttribute("textarea", "placeholder")) {

    } else {
    // fallback
    }

  2. Michael

    This doesn’t seem to work. I took your function and gave it “text” and “value” as arguments in FireFox 9.0.1 and it returned “false”. I like how simple and elegant the snippet is, but I just can’t get it to work. Does anyone know what’s going on with it?

Speak, my friend

At this moment, you have an awesome opportunity* to be the person your mother always wanted you to be: kind, helpful, and smart. Do that, and we'll give you a big ol' gold star for the day (literally).

Posting tips:
  • You can use basic HTML
  • When posting code, please turn all
    < characters into &lt;
  • If the code is multi-line, use
    <pre><code></code></pre>
Thank you,
~ The Management ~