admin管理员组

文章数量:1297086

Using JS, how can we find whether we can type into a html element or not. I am trying by paring ".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.

Using JS, how can we find whether we can type into a html element or not. I am trying by paring ".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.

Share edited Nov 4, 2014 at 10:05 Tim Down 325k76 gold badges460 silver badges542 bronze badges asked Nov 3, 2014 at 21:34 MohanMohan 1413 silver badges14 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 11

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".

Here is a typescript version.

function isEditableElement(el: EventTarget) {
  if (el instanceof HTMLElement && el.isContentEditable) return true;
  if (el instanceof HTMLInputElement) {
    // https://developer.mozilla/en-US/docs/Web/HTML/Element/input#input_types
    if (/|text|email|number|password|search|tel|url/.test(el.type || '')) {
      return !(el.disabled || el.readOnly);
    }
  }
  if (el instanceof HTMLTextAreaElement) return !(el.disabled || el.readOnly);
  return false;
}

@percy507 there is a typo. if (/|text|email|numb -> if (/text|email|numb

function isEditableElement(el: EventTarget) {
  if (el instanceof HTMLElement && el.isContentEditable) return true;
  if (el instanceof HTMLInputElement) {
    // https://developer.mozilla/en-US/docs/Web/HTML/Element/input#input_types
    if (/text|email|number|password|search|tel|url/.test(el.type || '')) {
      return !(el.disabled || el.readOnly);
    }
  }
  if (el instanceof HTMLTextAreaElement) return !(el.disabled || el.readOnly);
  return false;
}

Using the read only property.

From http://www.w3schools./jsref/prop_text_readonly.asp :

document.getElementById("myText").readOnly = true;

本文标签: javascriptCheck whether an HTML element is editable or not using JSStack Overflow