Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if HTML element is contenteditable from within Chrome Extension

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.

like image 767
c00000fd Avatar asked Sep 10 '14 07:09

c00000fd


People also ask

What is contenteditable attribute in HTML?

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.

How to know if the content is editable or not?

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!

What is the use of editable in HTML?

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.

How to make the content of an element editable?

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!";


1 Answers

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

like image 97
MaxArt Avatar answered Sep 26 '22 20:09

MaxArt