Estoy usando document.execCommand para poner en negrita y subrayar el texto, pero quiero hacer un botón que fuerce el texto para que no esté en negrita ni subrayado, en lugar de simplemente alternar. Tampoco puedo usar execCommand(“removeFormat”), ya que está causando problemas en mi programa. ¿Hay alguna solución que pueda usar para quitar la negrita o el subrayado del texto?
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 */ }Si desea eliminar todo el formato, puede hacerlo fácilmente reemplazando el HTML con su texto equivalente:
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> Si solo desea eliminar el texto en negrita, puede reemplazar los nodos en negrita con texto, como este: Si desea quitar el formato de algo individualmente, puede hacerlo así (ejemplo con negrita):
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>