I am using document.execCommand to bold and underline text, but I want to make a button that forces the text to be unbolded and not underlined, rather than simply toggling. I can’t use execCommand(“removeFormat”) either, as it is causing issues in my program. Is there a work around I can use to unbold/un-underline the text?
window.addEventListener('keydown', function (event) {
if (event.altKey){
if (event.code === 'Digit1') {
// Unbold, unhighlight, un-underline //
document.execCommand("hiliteColor", false, "transparent")
changeFont('7.5pt') /* This goes into a function to change the fontsize */
}
If you want to remove all formatting, you can easily do it by replacing the HTML with its text equivalent:
const editor = document.getElementById("editor");
document.getElementById("unformat").addEventListener("click", () => {
editor.innerHTML = editor.innerText;
});
<div id="editor" contenteditable>Mess <u>with me</u>, and <b>add crazy</b> formatting <b>to your heart's <u>content</u></b> then click <code>UNFORMAT</code></div>
<button id="unformat">UNFORMAT</button>
If you want to only remove bolded text, you could replace the bold nodes with text, like this: If you want to individually unformat something, you could do it like this (example with bolding):
const editor = document.getElementById("editor");
document.getElementById("unbold").addEventListener("click", () => {
// get all bolded elements
Array.from(editor.getElementsByTagName("b")).forEach(i => {
i.outerHTML = i.innerHTML; // replace the bold with its contents
});
});
<div id="editor" contenteditable>Mess <u>with me</u>, try <b>bolding</b> random <b>parts <u>then</u></b> click <code>UNBOLD</code></div>
<button id="unbold">UNBOLD</button>