2

I am trying to sync a contenteditable DIV with a textarea which is part of form.

I am pulling the innerHTML from the DIV but I would like to be able to remove nested formatting from the img tags (bold, italics, underline etc). It would probably be easier to remove any formatting on images before accessing innerHTML of the div as opposed to using regex on the html.

I could use:

    document.execCommand('removeFormat', false, null); 

But how might I only remove formatting on images?

(Also I need to use ALT tags on the images and it seems impossible to accomplish with execCommand / insertImage. Is this correct? I ended up following the suggestion on Contenteditable text editor and cursor position and am using insertHTML)

Thanks much!

Community
  • 1
  • 1
Mike Wolfe
  • 314
  • 1
  • 10

1 Answers1

1

Following @tim-down suggestion here is my attempt at navigating the DOM and removing text formatting from IMG tags.

Bonus will awarded for more elegant solutions.

Working example here: http://jsfiddle.net/tjzGg/

function setCaret() {
    var el = document.getElementById("editable");
    recurseDOM(el);
    el.focus();
}

function recurseDOM(el) {
    var nIndex = 0;
    var elNode = el.childNodes[nIndex];
    while (elNode) {
        var tag = elNode.tagName;
        if (tag) {
            if (tag.toUpperCase() == 'IMG') {
                var range = document.createRange();
                var sel = window.getSelection();
                range.selectNode(elNode);
                sel.removeAllRanges();
                sel.addRange(range);
                document.execCommand('removeFormat', false, null);
            } else if (elNode.childElementCount) {
                recurseDOM(elNode);
            }
        }
        nIndex++;
        elNode = el.childNodes[nIndex];
    }
}
Mike Wolfe
  • 314
  • 1
  • 10