JSFiddle - React, Tailwind, and code Playground
HTML
<div id="toolbar">
<button id="bold">Bold</button>
<button id="italic">Italic</button>
</div>
<div id="editable" contentEditable="true">
<div>Lorem Ipsum Lorem Ipsum</div>
</div>
CSS
#editable{
border: 1px solid #000000;
margin-top: 20px;
height: 50px;
font-family: Arial;
}
.bold{
font-weight: bold;
}
.italic{
font-style: italic;
}
JavaScript
var isOpera = !!window.opera || navigator.userAgent.indexOf(' OPR/') >= 0;
// Opera 8.0+ (UA detection to detect Blink/v8-powered Opera)
var isFirefox = typeof InstallTrigger !== 'undefined'; // Firefox 1.0+
var isSafari = Object.prototype.toString.call(window.HTMLElement).indexOf('Constructor') > 0;
// At least Safari 3+: "[object HTMLElementConstructor]"
var isChrome = !!window.chrome && !isOpera; // Chrome 1+
var isIE = /*@cc_on!@*/false || !!document.documentMode; // At least IE6
function replaceSelectedText(className) {
var selectedText, sel, range;
if (window.getSelection) {
sel = window.getSelection();
// check if selection has a class
if(isChrome){
if(sel.baseNode.parentElement.className){
console.log("isChrome className:" + sel.baseNode.parentElement.className);
sel.baseNode.parentElement.className = "";
return false;
}
}
if(isFirefox){
if(sel.anchorNode.nextElementSibling){
console.log("isFirefox className:" + sel.anchorNode.nextElementSibling.className);
sel.anchorNode.nextElementSibling.className = "";
return false;
}
}
selectedText = window.getSelection().toString();
//console.log(selectedText);
if (sel.rangeCount) {
range = sel.getRangeAt(0);
range.deleteContents();
var element = document.createElement('span');
element.className = className;
element.textContent = selectedText;
range.insertNode(element);
}
} else if (document.selection && document.selection.createRange) {
range = document.selection.createRange();
range.text = replacementText;
}
}
var toolbarButtons = document.querySelectorAll("#toolbar button");
//console.log(toolbarButtons);
for (var i = 0; i < toolbarButtons.length;...