I'm writing a Chrome Extension that needs to detect contenteditable
HTML elements (or the elements where a user can type into) on the page where my context script is injected into.
I'm currently doing this:
var objAll = document.getElementsByTagName("*");
for(var i = 0; i < objAll.length; i++)
{
obj = objAll[i];
if(obj.contentEditable &&
obj.contentEditable != 'inherit' &&
obj.contentEditable != 'false')
{
//Yes, this is a content editable element!
}
}
But my method doesn't seem to work in all the sites that I tested it on.
I'm curious, what am I missing there?
PS. Because it's a content script I am not using jQuery to make it more robust.
HTML | contenteditable Attribute. It is used to specify whether the content present in the element is editable or not. When this attribute is not set in an element, this element will inherit from its parent element. Syntax: Attribute: It is mainly an instance of a Global Attributes and it can be used in any HTML elements.
If the attribute value is true then the content is editable and if the attribute value is false the content is not editable. Supported Browsers: The browser supported by contenteditable attribute are listed below: Attention reader!
It is used to specify whether the content present in the element is editable or not. When this attribute is not set in an element, this element will inherit from its parent element.
The element's content is editable if its parent element is editable button.innerHTML = "Enable content of p to be editable!"; button.innerHTML = "Disable content of p to be editable!";
contentEditable
is a property that's implied by the contenteditable
attribute. What you really need to check is the isContentEditable
property, which is a boolean that tells if the element has an editable content or not:
if (obj.isContentEditable) {
// do stuff
}
But instead of getting all the elements and filtering them, just select all the contenteditable
elements:
var contEditables = document.querySelectorAll('[contenteditable]');
for (var i = 0; i < contEditables.length; i++) {
// do stuff
}
In fact, an element has editable content if and only if it has a contenteditable
attribute, whether is an empty string or not.
Live demo
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With