user592748
user592748

Reputation: 1234

contenteditable not working on dynamically generated elements

I am dynamically creating an unordered list and adding items to it on a click of a button. I append this to a section that has contenteditable attribute set true. However, I do not see it working. I did set the contenteditable attribute to true even for the list but I guess it is supposed to inherit that from the section it is appended to. Here is the code of what I am doing.

// create text input
var categoryInput = document.createElement('input')
// create button to add the text entered to a list
var btnAddToList = document.createElement('input');
btnAddToList.type ="button";
//create a section to add a list to 
var section =  document.createElement('section');
var ul=document.createElement('ul');
section.appendChild(ul);
section.contenteditable = "true";
ul.contenteditable = "true";
//create an event handler to add to the list
if (btnAddToList.addEventListener) {   btnAddToList.addEventListener('click', function () { addToList(ul, categoryInput.value);});
} else if (btnAddToList.attachEvent) {
btnAddToList.addEvent('click', function () { addToList(ul, categoryInput.value);});

Here is the function I call

function addToList(unorderedlist, inputText) {

    if(inputText.length == 0) {
        alert("Add Text");
        return;
    }   


    var listitem = document.createElement('li');
    var listvalue = document.createTextNode(inputText);
    listitem.appendChild(listvalue);
    unorderedlist.appendChild(listitem);
}

What am I doing wrong or not doing? Any help appreciated. Thanks

Upvotes: 1

Views: 7031

Answers (2)

rusmus
rusmus

Reputation: 1665

You need to set the attribute, not the property:

section.setAttribute('contenteditable', 'true');

Instead of

section.contenteditable = "true";

Some more info here and here (in the context of jQuery, but covers the topic splendidly nonetheless).

My current understanding of the difference is that attributes are the things you can set through markup (id, class, contenteditable, etc.), whereas properties are the properties of the actual javascript objects representing the DOM nodes. As the linked article mentions, the two are often kept in sync by the browser, but not always.

Edit: As Tim Down states in his answer, while the above works (setting the attribute), the actual problem is that the name of the property is cased wrong. It should be

section.contentEditable = "true"; //Note the upper case 'E'

The reason setting the attribute works, is that attributes are case-insensitive.

Upvotes: 2

Tim Down
Tim Down

Reputation: 324517

The property is contentEditable (note upper-case 'E'), not contenteditable.

section.contentEditable = "true";

Upvotes: 3

Related Questions