Demo is here
I have a contenteditable div. I want the functionality in the div as follows:
When I click on red anchor tag, the new text that I will write will be
You could make use of HTML editing APIs for such use-cases. Reference here: https://dvcs.w3.org/hg/editing/raw-file/tip/editing.html
In short, use the execCommand
along with styleWithCSS
to achieve what you want. styleWithCSS
will let you control whether CSS or HTML formatting should be generated by the execCommand method into the document. Pass true
to use the CSS styling instead of generating the font tag.
Try it out below...
Example Snippet:
var
red = document.getElementById("red"),
blue = document.getElementById("blue"),
reset = document.getElementById("reset")
;
red.addEventListener("click", function() { setColor("#f00"); });
blue.addEventListener("click", function() { setColor("#00f"); });
reset.addEventListener("click", function() { setColor("#000"); });
function setColor(color) {
document.execCommand('styleWithCSS', false, true);
document.execCommand('foreColor', false, color);
}
Red | Blue | Reset |
this is some text
This will generate HTML with CSS applied, like this:
this is some text
Hope that helps.
.