views:

49

answers:

2

I want retrieve the text content from a contentEditable div through javascript. What are the options of doing this? I've tried innerHTML but it doesn't work.

A: 

use jQuery and do

var content = $('#my-contenteditable-div').html();

also look up these links:

http://west-wind.com/Weblog/posts/778165.aspx

http://stackoverflow.com/questions/3455931/extracting-text-from-a-contenteditable-div

Moin Zaman
A: 

You can use the editable <div>'s innerText property in IE and textContent property in other browsers but they are not implemented exactly the same. The most reliable cross-browser approach is to iterate over the text nodes within the editable <div>:

function getText(node) {
    var textBits = [];
    if (node.nodeType == 3) {
        textBits.push(node.data);
    } else {
        var childCount = node.childNodes.length;
        if (childCount) {
            for (var i = 0; i < childCount; ++i) {
                textBits.push(getText(node.childNodes[i]));
            }
        }
    }
    return textBits.join("");
}

var div = document.getElementById("your_div");
alert( getText(div) );
Tim Down