Execute the JavaScript `execCommand("ForeColor")` command to remove the highlighting

Is there a way in JavaScript to dynamically remove text highlights that were applied using the execCommand("HiliteColor") method? I want to check if the selected text is within a highlighted span and then remove the highlight. Additionally, how can I handle situations where only part of the selected text is highlighted? I've attempted to manually add spans and remove highlights using the following code:

document.getElementsByClassName('highlight').remove();

alert(window.getComputedStyle(document.getElementById("pages"), null).getPropertyValue('background-color'));

alert(document.getElementById("pages").style.backgroundColor);

I tried checking the background color and removing the class 'highlight' but haven't had success yet.

You can view my project on CodePen at: https://codepen.io/pokepimp007/pen/wxGKEQ

SOLUTION

I have created a function that accepts a color parameter when a button is clicked. Clicking the "Delete Highlight" button sends the color parameter as "transparent":

function Highlight(color) {
  document.designMode = "on';
  var sel = window.getSelection();
  sel.removeAllRanges();
  var range = document.createRange();
  range.setStart(editor.startContainer, editor.startOffset);
  range.setEnd(editor.endContainer, editor.endOffset);
  sel.addRange(range);
  if (!sel.isCollapsed) {
    if (!document.execCommand("HiliteColor", false, color)) {
      document.execCommand("BackColor", false, color);
    }
  }
  sel.removeAllRanges();
  document.designMode = "off";
}

Answer №1

Upon noticing your use of jQuery, I have included the jQuery tag in your post.

This solution should work like a charm.

$('#removeHighlight').on('click', function(){
   $('.highlight').each(function(){
       $(this).replaceWith($(this).text());
   })
})
.highlight {
  background: yellow;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>This is a silly piece of text with <span class="highlight">highlight_1</span> in it to showcase the power of jQuery in removing things like  <span class="highlight">highlight_2</span> from an HTML document. Feel free to click the button to witness the magic of <span class="highlight">highlight_3</span>.</p>
<button id="removeHighlight">Remove</button>


If you only wish to remove a single highlight, follow these steps.

$('#removeHighlight').on('click', function(){
     $('.highlight').first().replaceWith($('.highlight').first().text());
})
.highlight {
  background: yellow;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>This is a silly piece of text with <span class="highlight">highlight_1</span> in it to showcase the power of jQuery in removing things like  <span class="highlight">highlight_2</span> from an HTML document. Feel free to click the button to witness the magic of <span class="highlight">highlight_3</span>.</p>
<button id="removeHighlight">Remove 1</button>


Alternatively, if you prefer to remove it upon clicking,

$('p').on('click', '.highlight', function(){
   $(this).replaceWith($(this).text());
})
.highlight {
  background: yellow;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>This is a silly piece of text with <span class="highlight">highlight_1</span> in it to showcase the power of jQuery in removing things like  <span class="highlight">highlight_2</span> from an HTML document. Feel free to click the button to witness the magic of <span class="highlight">highlight_3</span>.</p>

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

Determine the latest date within each group and display the corresponding output value

I am seeking a way to showcase only the most recent value for each group. For example, in the CSV data provided below, the total amount of Bagels in the Cinnamon Raisin variety were collected during three different sampling periods: May 2017, March 2017, ...

Searching for a jquery control for adjusting audio volume that is not in the form

Has anyone come across a JavaScript plugin that can control music volume? I've already written all the necessary functionality, but now I just need the user interface. Instead of a traditional slider, I'm looking for something more unique like a ...

Move the button above a hyperlink in a Bootstrap carousel

Is there a way to add a top-right button on each slide that will be positioned over the carousel-control link? How can I achieve this design? Currently, the buttons appear under the carousel-control as shown below: .myButton { position: absolute; ...

Can existing servers support server side rendering?

I am currently working on building a Single Page Application (SPA) using the latest Angular framework. The SPA will involve a combination of static HTML pages, server side rendering, and possibly Nunjucks templating engine. My dilemma lies in the fact th ...

Django Accordion Table Template

I have a Django model that populates a table with objects from a database. What I'm trying to achieve is, when a row in the table is clicked, to use JS or JQuery to accordion a table of objects that are connected as foreign keys to the main object. A ...

difficulty with displaying the following image using jquery

I have referenced this site http://jsfiddle.net/8FMsH/1/ //html $(".rightArrow").on('click',function(){ imageClicked.closest('.images .os').next().find('img').trigger('click'); }); However, the code is not working ...

The radio button fails to register the selection

I need to ensure a radio button is checked if it has a value, but the output of my code is not displaying as expected: <input id="radio2" type="radio" checked="checked" value="2" name="radio"> Despite specifying checked="checked", the radio button ...

What causes the default styling of a browser user agent to be altered when a background image is added to an input button?

Take a look at this example: http://jsfiddle.net/eJSGn/ input{ padding-left: 20px; } input:last-of-type{ background: url(http://skiorboard.com/wp-content/uploads/2014/03/search.png) no-repeat; background-size:15px 15px; } <in ...

Storing data on your local machine using Electron

I am in need of help with my template files which have variable strings. I want to create a basic input form using Electron (https://www.electronjs.org/) and save the resulting output file on the user's device. Could someone recommend a module that e ...

What is the best way to eliminate excessive margin-bottom on a floating image?

Is it possible to maintain the same margin at the right and bottom of an image when using <img> inside <p><img style="float:left">dummy text dummy text dummy text dummy text</p>? ...

Tips on utilizing HTML tags in shiny context to highlight or potentially enlarge the font size for sprintf使

Can anyone help me figure out how to bold or increase the font size for my sprintf in R? I attempted the code below but it didn't work as expected. Instead of bolding the text, the "<strong" tags became part of the label. Any suggestions on how to ...

The context of the Nuxt.js3 plugin loses its definition

Currently, I am working on a project that involves Nuxt.js3 and supabase integration. In my plugins/supabase.server.js file (I am still unsure whether using server or client is the best approach), I want to call "supabase = createClient(~~)" from index.vu ...

Should CSS properties be applied directly to the html tag?

Surprisingly, I recently discovered that it's possible to set the background-color of the html tag. It seems strange since I always thought the body was responsible for containing the first rendered tag. I used to believe that the html tag was just a ...

Duplicate the canvas onto a new canvas

One of the functions I am using involves copying an old canvas to a new canvas. Here is the code snippet for this functionality: function cloneCanvas(oldCanvas) { //create a new canvas var newCanvas = document.createElement('canvas&a ...

I'm having trouble understanding why the MUI CORE basic rating code is returning undefined for setValue. Can anyone help

My first experience with MUI CORE was not smooth as I encountered an error when trying to use active rating and the set value is not defined i mport './App.css'; import 'bootstrap/dist/css/bootstrap.min.css'; import Movie from './ ...

Tips for maintaining i18n locale slugs and ensuring i18n consistency when reloading in Next.js

I'm currently utilizing next-translate. The default recognition of my routes is as follows: /about <--- /de/about /es/about However, I would like to set a specific locale for all paths: /en/about <--- /de/about /es/about Below is ...

Effortless link to a Gremlin database using a JavaScript app

I apologize for my lack of technical knowledge, but I am struggling to solve this issue despite studying the documentation. My goal is to establish a connection with a standard Gremlin DB (Cosmos) using gremlin. While it works well from the server, encoun ...

Looking for assistance in determining a solution for progress bar implementation

Currently, I am developing a simple application using web technologies like HTML, CSS, and jQuery Mobile. This app enables me to create goals and save them to a listview using the <li> element. Every <li> representing a goal will have an assoc ...

The input field does not accept any values even after setting it to be editable

Hey there! I have a specific requirement where I need to edit certain fields by clicking on an edit link. Initially, these fields will be disabled and in a readonly state. Once I click on the edit link, the field should become blank and editable. The issu ...

Exploring the Link Between jQuery and HTML

Is it possible to connect between an HTML file and a jQuery file? Here is an example scenario: jquery-test.js: $(document).ready(function(){ $('#inputForm').submit(function(){ $('#inputForm :text:not("#submit")').each(func ...