Reputation: 2056
I have this:
<input type="button" value="B" onclick="document.execCommand('bold', false, '');" />
<div contenteditable="true">Lorem Ipsum...</div>
The document.execCommand
works fine. But what if a want to add a custom tag, like <customtag></customtag>
surrounding the selected text?
The button need to add the tag to the selected text or eliminate it if it already has it.
Is there a HTML-only solution for this. If not, any pure Javascript solution?
Upvotes: 4
Views: 2283
Reputation: 8793
You need the insertHTML
command:
Basic usage:
<input type="button" value="html" onclick="document.execCommand('insertHTML', false, '<customtag>'+window.getSelection()+'</customtag>');" />
To toggle the custom tag on and off, a more complicated logic is needed:
<input type="button" value="html" onclick="document.execCommand('insertHTML', false, toggle(window.getSelection());" />
function toggle(txt)
{
return is_enclosed_within_a_customtag(txt)
? strip_custom_tag_off(txt)
: "<customtag>"+txt+"</customtag>"
;
}
Function is_enclosed_within_a_customtag
might be implemented, at least, like this:
function is_enclosed_within_a_customtag(txt)
{
return txt.startsWith("<customtag>") && txt.endsWith("</customtag>");
}
... and be called passing window.getSelection().toString()
as parameter.
Upvotes: 4