特定の状況で contenteditable div から選択した HTML を取得しようとしています。まず、 Get selected element's outer HTMLとGet Selected HTML in browser via Javascriptからの質問を読んだことをお伝えします。
そして、私はRedactor http://imperavi.com/redactor/を使用しています
そこで、選択した HTML を取得するために次の関数を試しました。
function getSelectionHtml() {
var html = "";
if (typeof window.getSelection != "undefined") {
var sel = window.getSelection();
if (sel.rangeCount) {
var container = document.createElement("div");
for (var i = 0, len = sel.rangeCount; i < len; ++i) {
container.appendChild(sel.getRangeAt(i).cloneContents());
}
html = container.innerHTML;
}
} else if (typeof document.selection != "undefined") {
if (document.selection.type == "Text") {
html = document.selection.createRange().htmlText;
}
}
return html;
}
状況は次のとおりです。イタリック体のテキストのようなものがあり、それを選択し、DOM を変更して太字にします。
テキストを選択して太字にすると、HTML は次のようになります。
<span class="bold"></span><strong><span class="bold" data-redactor="verified" data-redactor-inlineMethods="">fermentum</span><span></span></strong>
ページ内の別の場所をクリックします。テキストの選択が解除されます。
テキストを 2 回目に選択してイタリック体にすると、次のようになります。
<em>発酵
ご覧のとおり、2 回目は太字であると判断できる要素を取得できません。
そのため、Internet Explorer 10 では動作しません。Firefox では動作します。Chromeでは機能しません。
これ以外の contenteditable div から選択した HTML を取得する効果的な方法はありますか?