One effective way to remove bold formatting from text that has been altered using execCommand

While I am utilizing document.execCommand to bold and underline text, what I really need is a button that can unbold the text and remove any underlining instead of just toggling them. Unfortunately, using execCommand("removeFormat") is causing some issues within my program. Do you know of any workaround I could use to achieve this unbolding/un-underline effect?

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 */
  }

Answer №1

To completely eliminate all formatting, simply substitute 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&apos;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: Should you wish to individually unformat something, it can be done in a similar manner (demonstrated 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; 
  });
});
<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>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The backface remains visible despite being designated as "hidden"

I have successfully created a "flip card" in CSS3, where the card flips downward to reveal the other side when a user hovers over it. I have ensured that the back face is not visible by setting backface-visibility to hidden. However, despite my efforts, th ...

Compensating for the variations in camera rotation specifications between standard and virtual reality mode within the aframe framework

I'm currently developing a WebVR project using Aframe that features multiple miniature 3D scenes (approximately eight) surrounding the viewer. To view each scene, users must rotate their viewpoint accordingly. Since the number of scenes surpasses wha ...

Am I utilizing React hooks correctly in this scenario?

I'm currently exploring the example, but I have doubts about whether I can implement it in this manner. import _ from "lodash"; ... let [widget, setWidgetList] = useState([]); onRemoveItem(i) { console.log("removing", i); ...

Arrange the array so that the item is placed at the beginning while maintaining the original order

Currently facing a roadblock with this particular issue. I am attempting to create a function that accepts an index as input and rearranges the element at that index in an array to be placed at the beginning, while keeping the order of the other elements a ...

Using Angular's async, you can retrieve a value returned by a promise

Within the library I am currently utilizing, there is a method called getToken which can be seen in the following example: getApplicationToken() { window.FirebasePlugin.getToken(function(token) { console.log('Received FCM token: ' + to ...

Sending a parameter to a different function (on a separate webpage)

At the start of my webpage, there are two radio buttons on the first page, each with its own value. Upon clicking a link to move to the second page, a for loop is activated to grab the value of the selected button. The script has been tested and works as e ...

Vercel - Deploying without the need to promote the project

How can I deploy my Nextjs app to production in a way that allows me to run E2E tests on a "pre-prod" version before promoting it to prod, similar to using a preview URL without public traffic being directed there? I am looking for a process where I can v ...

Improving React efficiency: What techniques can be used to prevent the entire component from re-rendering every time a prop changes?

Issue at Hand I created a custom component named PageLayoutSideBar.tsx that accepts two props: sideBar and content. This component is designed to make it easy to display the sideBar and page content with the appropriate styling and sidebar width. My conce ...

Having trouble retrieving the value of an object in Angular

I have an AngularJS factory named 'userFactory' that I'm using: app.factory('userFactory', function($window) { var auth = { isLogged: false, user: "a", check: function() { if ($window. ...

Issue with remove functionality in Vue js implementation causing erratic behavior in my script

Within my Vue.js code, I have a functionality that displays categories from an API. When a category is clicked, it is added to the AddCategory array and then posted to the API. I have also implemented a button called RemoveAll which successfully empties th ...

Elegant Bootstrap 4 Carousel featuring a glimpse of the upcoming slide alongside the primary carousel item

I am in search of a straightforward Bootstrap 4 carousel that showcases a glimpse of the next slide on the right. Despite exploring similar questions, I have not found a suitable solution. The links to those questions are: 1)Bootstrap carousel reveal part ...

Using Javascript's Speech Recognition to activate a button

I am new to using JavaScript Speech Recognition and decided to work with the Annyang library. My goal is to automatically trigger the "show date" button when the user says 'hello', without actually clicking the button. However, I've been fac ...

Click here to navigate to the same or a different page using an anchor

I'm currently implementing this code: $(function() { $('a[href*=#]:not([href=#])').click(function() { if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostna ...

Exploring JS inheritance concepts including the use of .call, .create,

I've recently started learning Javascript and I'm a bit perplexed by the concept of Inheritance. The code snippet below is from a phaser tutorial where Bullet seems to inherit from Sprite. Firstly, it employs the call method which, as far as I kn ...

Create a dynamic animation using three.js

I am currently developing an application that optimizes pack placement in a truck using three.js for displaying 3D results. Below is the code snippet I'm working with: My goal is to create a moving scene where boxes are displayed one by one and move ...

Arrange an array of objects to a specific sequence

I am currently working with an array of objects that contain a property named 'CODE'. [ { ID: 168, NAME: "First name", CODE: "AD" }, { ID: 167, NAME: "Second name", CODE: "CC" }, { ID: 169, NAME: "Third name", ...

Using an onclick function to increment and decrement values

Can anyone help me figure out how to reverse a function onclick? Here is the function: var theTotal = 0; $('button').click(function(){ theTotal = Number(theTotal) + Number($(this).val()); $('.total').text(theTotal); }); ...

The error message "Seed is not defined" is raised when the program attempts to

I'm currently diving into fullstack vue and I'm perplexed by the error occurring in this particular scenario. window.Seed = (function () { const submissions = [ { id: 1, title: 'Yellow Pail', ...

What is the process of setting up Express as an API web server and integrating a custom document renderer as middleware?

I have developed a code generator and I want to be able to execute it on the server. The generator utilizes pure native ECMA6 JavaScript to render HTML markup, but it is transpiled to ES5 before runtime using Babel and WebPack. I am looking to use this on ...

Having trouble with the Mysqli query not functioning properly in PHP code after being dispatched via Ajax

I am encountering a problem with a specific Myqsli query. $sqlselect = "SELECT visitatori_id FROM visitatori WHERE visitatori_nome='".$nome."' AND visitatori_cognome='".$cognome."' AND visitatori_orastart='".$time."' AND v ...