Is there a way to delete highlighted text without using execCommand and changing the font color

With my current use of JavaScript, I am able to highlight or bold a selected text range successfully. However, I am unsure how to undo the bold and unhighlight the text if the button is clicked again and the selected range is already bolded or highlighted.

I am unable to use doc.execCommand or jQuery due to using it in an Android webview. Using doc.execCommand takes a significant amount of time (1 second or more) to work on large texts, whereas JavaScript functions instantaneously. Utilizing jQuery (zepto or others) causes the text to load very slowly in the webview, while without it, the loading time is at most 1 or 2 seconds.

=)

This is what I currently have to make the selected text bold:

function bold() {
    var range               = window.getSelection().getRangeAt(0);
    var selectionContents   = range.extractContents();
    var span                = document.createElement("span");
    span.appendChild(selectionContents);
    span.setAttribute("class","bold");
    span.style.fontWeight  = "bold";

    range.insertNode(span);
}

And for highlighting (note: color will be chosen by the user through a color picker and returned as #xxxxxx):

function foreground() {

var range               = window.getSelection().getRangeAt(0);
var selectionContents   = range.extractContents();
var span                = document.createElement("span");

span.appendChild(selectionContents);

span.setAttribute("class","foreground");
span.style.color            = "#" + colorbyUser;

range.insertNode(span);}

I believe that styling such as bold/italic/strike/strikethrough/underline can be achieved with specific CSS classes added or removed easily. However, adjusting background and foreground colors may require individual handling for each selection (letter/word or more).

Apologies for the imperfect English =x

Edit for C-smile

I understand now, but I am uncertain how to target the element in this scenario:

<span class="bold">Hello   <span class="underline">C</span>-<span class="italic">Smile</span></span>

How can I remove the bold from "Hello" if only "HelLo" is selected, without affecting the bold formatting of "C-Smile"?

Is this achievable without relying on jQuery (which slows down loading time for big documents) or doc.execCommand (slows down processing time for big documents)?

Answer №1

In the case where you have enclosed a range within a <span class="highlight"> element, you will need to remove this enclosing tag by extracting the content node of the span and replacing the span with its content node.

This functionality is essentially what $.unwrap() accomplishes in jQuery.

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

Ways to retrieve the data within the tinymce text editor for seamless submission through a form

I am a beginner with TinyMCE and I am working on integrating the editor into my Laravel project. So far, I have managed to get it up and running, but I am struggling with retrieving the content from the editor and passing it to the controller for database ...

Utilizing AJAX in Django applications

I'm currently working on integrating a basic AJAX function with Django, but I seem to be facing some issues. The request.is_ajax() function is returning False, and using event.preventDefault() doesn't prevent the form from getting submitted. Her ...

Placing a small image on top of multiple images using CSS

I am facing a CSS issue and I need help with positioning a small image (using position absolute) like a warranty badge on top of larger images. The challenge is to ensure that the badge is fixed at the bottom left corner of each image, despite variations ...

Challenges with HTML and JavaScript

Struggling to get this code to work properly with Node.js. const express = require('express') const app = express() app.use(express.static('public')) //includes content of public folder app.get('/', function (req, res){ ...

Error found in Google's privacy page HTML code

Reviewing the html code of Google's Privacy Page, I observed the following header: <!DOCTYPE html> <html lang="en"> <meta charset="utf-8> <title>Google Privacy Center</title> <link rel="stylesheet" href="//www.g ...

I am facing an issue where my Javascript hide and show function is not working properly when clicked. Despite not giving

I am currently working on a Javascript onClick function to toggle the visibility of content in a lengthy table. I initially set part of the table's class to display: "none" and added a button to show the hidden content when clicked. However, nothing i ...

What steps should I follow to change the appearance of this object to match this?

Attempting to modify the value of an object nested within an array, which is in another object. The nesting might be a bit complex... Here's how it currently looks { household and furniture: [{…}, {…}], school stuffs: [{…}, {…}] } M ...

Button click event not triggering JavaScript execution

I am experimenting with HTML, PHP and JS and have encountered a problem. Here is my code: <html> <head> <title> Dummy Code </title> <script> sendMail(){ <?php $to = '<a href="/cdn-cgi/l/email-protection" class ...

Attempting to send a POST request, only to be informed by the form that it is devoid of

I have been struggling with this problem for some time now. I implemented the category_create_post functionality in the categoryController, and everything seems to be set up correctly. I also configured the category_form.ejs to accept user input. However, ...

The Typescript compiler is unable to locate the module './lib'

I'm currently integrating the winston-aws-cloudwatch library into my TypeScript server-side application. If you want to replicate the issue, I have provided a SSCCE setup on GitHub. Here are the details: index.ts import logger from './logger& ...

Initiate the Material TextField onChange event from within a nested component

I am currently working on a component that looks like this: class IncrementField extends Component { inputRef; changeValue() { this.inputRef.value = parseInt(this.inputRef.value) + 1; } render() { const { ...other } = this.props; return ( ...

Steps for retrieving information from a View, transferring it to a Controller, and subsequently forwarding it to another View

Hello everyone! So, I have a situation where I need to pass values from a view using @Html.ActionLink to a controller and then pass them to a new view. I've tried creating a ViewModel that matches the values I need, but when I try to show these result ...

Can the outcomes be showcased again upon revisiting a page?

Whenever I navigate away from and return to my filter table/search page, the results vanish. I'm looking for a way to preserve the results without reloading the page. Essentially, I want the page to remain as it was originally, with the search results ...

Connect my Vue.js model data to the object that will be used for submission

I need help figuring out how to bind data from my input field into my Vue.js model. I've tried putting the UnitName inside the model but it's not working. Can someone provide some guidance on how to achieve this? new Vue({ el: "#app", da ...

Uploading Files within Angular FormArray

I am facing an issue with my formArray which contains file upload inputs in each element. Whenever I upload an image in one input, it changes the values of other file inputs in different rows. https://i.stack.imgur.com/3haZW.png Current Behavior: Uploadi ...

Transform an array of strings into an array of object IDs

Recently, I encountered an issue with transforming an array of strings into object IDs using mongoose type. Unfortunately, my attempt was unsuccessful as it seems the method only works for single string inputs, not arrays. let stringObjectIdArray = [&apos ...

Bokeh is having trouble loading from the CDN

I am currently attempting to embed a plot along with its data by utilizing autoload_static within a straightforward html page that I wish to view locally on my computer. According to the documentation, all I need to do is place the .js file in the specifie ...

Calling http.get one after the other without knowing the length of the list

Suppose I have a list of URLs as follows: var myurls = ['http://server1.com', 'http://server2.com', 'http:sever2.com', etc ] Each URL is considered a "fallback" and should only be used if the previous one is unreachable. Thi ...

Problem with uploading special characters (čžćšđ) in Uploadify

I've encountered an issue with uploading images using . When I upload images with characters such as (čžćšđ) like "čžćšđ.jpg", the characters get corrupted and the uploaded image ends up looking like čćžšđ.jpg. How can I pr ...

I am experiencing issues with the detection of mouseover events on an SVG circle

I am currently working on a d3 map with zoom functionality that displays circles representing different cities. However, I am facing an issue where the mouseover event for the circles (which shows tooltips and clicking reveals some lines) seems to only reg ...