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

Refreshing a PNG file without the need to refresh the entire page

Developed a captcha using imagestring imagestring($image, 5, 5, 30, $text, $text_color); imagepng($image,"captcha_image.png"); imagepng($image,"captcha_image.png"); The code snippet above shows part of the implementation. <img ...

What causes the disappearance of CSS styles when attempting to modify the className in react js?

I am currently working on a basic react application, and I am trying to dynamically change the name of a div element using the following code snippet - <div className={'changeTab ' + (page.login ? 'leftSide' : 'rightSide')} ...

Filtering Sails.js query model based on a collection attribute

Imagine I have these models set up in Sails.js v0.10: Person.js module.exports = { attributes: { name: 'string', books: { collection: 'book', via: 'person' } } }; Book.js module.exports = { ...

Is there a way to exclude certain URLs from the service worker scope in a create react app, without the need to eject from the project?

Is there a way to remove certain URLs from a service worker scope in create-react-app without needing to eject? The service worker is automatically generated, and it seems impossible to modify this behavior without undergoing the ejection process. ...

Issue: Unable to assign type 'FormDataEntryValue' to type 'string'. Type 'File' cannot be assigned to type 'string'

After retrieving data from the formData, I need to pass it to a function for sending an email. Error: The error message states that 'FormDataEntryValue' is not compatible with type 'string | null'.ts(2322) definitions.ts(119, 3): The e ...

Encountering a Vercel deployment failure due to a TypeError: The 'split' property cannot be read from undefined within several objects

I'm having trouble deploying my web application for the first time and encountering this error on Vercel: TypeError: Cannot read property 'split' of undefined at Object.3qS3 (/vercel/path0/.next/serverless/pages/[collection]/[templateId].j ...

Why is there a false positive in the onChange event for the number type in React TypeScript?

I encountered an error on line 24 Argument of type 'string' is not assignable to parameter of type 'SetStateAction'.ts(2345) This issue occurred while working with TypeScript for a React experiment. const App: React.FC = () => ...

What is the best way to create and implement custom declaration files that are not available on @types or DefinitelyTyped?

I have encountered a situation where I am using an npm package named foo that is not available on DefinitelyTyped or may be outdated. Despite this, I still want to consume it under stricter settings like noImplicitAny, so I need to create custom definition ...

Tips for automatically refreshing a Next.js application following an update in an external library

I have a monorepo containing two applications: The first is a Next.js web app The second is a UI library using Tailwind CSS and Microbundle Currently, the only way I can get the web app to recognize changes made in the UI library is by following these st ...

Select a specific division element using a pseudo element

My goal is to specifically target the third div in my HTML code with a class called .counter-wrap. When viewed on a mobile device, this particular div has a margin-bottom of 40px. I am looking to eliminate the margin-bottom for only the third stacked div n ...

Handling exceptions in AngularJS router-ui resolve functionality

In my app, I have the parent route listed below: .state('app',{ url: '/app', templateUrl: 'views/app.html', resolve: loadSequence('modernizr','moment'), ...

The fancybox's excess content is concealed

I've recently integrated fancybox 2 into my project and have encountered an issue when appending HTML content to the modal. I disabled scrolling, but now any overflowing content is being hidden. Could this be related to the max-height of the modal? Ho ...

Utilizing tags within the pre tag to incorporate additional styles

Using pre tags to display code works well, but I need to style certain parts of the code in green. However, when I wrap the desired code in a <div> tag with styling, it affects formatting by adding newlines and swallowing spacing. How can I achieve t ...

Perform a calculation using data from one schema and store the result in a different schema within MongoDB using Node.js

var ItemSchema = new Schema({ name: {type: String}, size : {type: String}, price : { type: Number} }); var SizeSchema = new Schema({ sizeName: {type: String}, dimensions : {type: String} }); F ...

Display of undefined data in Ajax success response

After receiving an array object data in the Ajax success result, I am trying to print li tags but they are showing as undefined. This is my Ajax code: $.ajax({ 'method': 'GET', 'url': base_url +'party/sel ...

Unable to add ngRoute dependency in Angular

I'm facing an issue while trying to set up a basic Angular route in my current project, encountering the error: Uncaught Error: [$injector:modulerr] I have ensured that I have injected ngRoute as a dependency in my module and included the angular-rou ...

Discover the color value within an array that begins with the "#" symbol

In my PHP code, I have written a function that extracts values from a CSS file and creates an array. Now, I need to loop through this array and create another array that only contains color values (strings starting with #). The challenge is that the length ...

Eliminating the bottom border of all buttons, except for the last three buttons in the list, solely using pure JavaScript, unless alternative methods are available

I have 3 sets of buttons, with each set containing 9 buttons stacked in 3 columns inside an ordered list (ol) within list items (li). I have removed the bottom border of the buttons to avoid double borders since they are stacked on top of each other withou ...

Ways to remove the highlighting from a selected list item using CSS/Javascript

I have a problem with a list of images and keywords that act as selections for users. When a user clicks on a selection, it highlights the corresponding image using CSS shadow. However, I am trying to figure out how to deactivate this highlight later on, e ...

Having issues with inline conditional statements in Angular 5

There is a minor issue that I've been struggling to understand... so In my code, I have an inline if statement like this: <button *ngIf="item?.fields?.assetType !== 'tool' || item?.fields?.assetType !== 'questions'">NEXT< ...