Search code examples
javascriptcontenteditable

Check whether an HTML element is editable or not using JS


Using JS, how can we find whether we can type into a html element or not. I am trying by comparing ".tagName" to "INPUT" or "TEXTAREA" but it fails to differentiate between a regular input text/email element and a radio-button or a submit-button.

I also tried with ".isContentEditable" but when the element is "inherited" then I am unable to differentiate.


Solution

  • For inputs and textareas, check tagName and type, not forgetting newer HTML5 input types such as email. Here's a snippet from my code for testing this on an element stored in a variable called el:

    var nodeName = el.nodeName.toLowerCase();
    if (el.nodeType == 1 && (nodeName == "textarea" ||
        (nodeName == "input" && /^(?:text|email|number|search|tel|url|password)$/i.test(el.type)))) {
        // Do stuff
    }
    

    For other elements, the isContentEditable property works in all cases and should only ever return a Boolean, never a string such as "inherit".

    Finally, there is the possibility that the whole document has been made editable using the document.designMode property, in which case document.designMode will have the string value "on".