defiant underscore refusing to function

I'm currently working on a text editor, but I'm facing an issue with the remove underline functionality that doesn't seem to be working as expected. For reference, you can check out a working code example here: jsfiddle

Below is the part of the code that's causing the problem:

else if (tag == "u") {
    sell = window.getSelection().getRangeAt(0);

    if (selectionIsUnderlined()) {
        node = range.createContextualFragment("<font style='text-decoration: none !important'>" + sell + "</font>");
    } else {
        node = range.createContextualFragment("<u>" + sell + "</u>");
    }

    range.deleteContents();
}

Any suggestions or ideas on how to fix this?

Answer №1

One challenge that arose when trying to remove the underline was that the process did not account for the <u> element wrapping the text. As a solution, the content within the <u> tags was removed and replaced with new content enclosed in <font> tags.

An attempt was made to move up one node to check if it was an <u> element before removing it:

if (selectionIsUnderlined()) {
    node = range.createContextualFragment(
           "<font style='text-decoration: none !important'>" + sell + "</font>");
    var nd = sel.anchorNode;
    if(nd.nodeName!=='span'){
        nd = nd.parentNode;
    }

    if (nd) {
        nd.remove();
    }

You can view the updated fiddle by clicking on this link: here

PS:- Keep in mind that this approach is experimental. It's recommended to evaluate its performance, browser compatibility, and other pros/cons before implementation.

Answer №2

Consider trying out this approach:

var nodeList="";
var divCount=0;

if (selectionIsUnderlined()) {
   nodeList+="<div class=underline>";
   divCount++;
}

if(selectionIsBold()){
   nodeList+="<div class=bold>";
   divCount++;
}

nodeList+= sell;

Don't forget to close your divs.

.underline{
   text-decoration: underline;
}

and so forth..

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

Challenge with Context Api state not reflecting the latest changes

Hey there, I've got this function defined in AuthContext.js: let [authTokens, setAuthTokens] = useState(null) let [user, setUser] = useState(false) let [failedlogin, setFailedlogin] = useState(false) let loginUser = async (e) => { ...

Add a variety of icons to every item in a list using HTML

Is there a way to display multiple icons on the left side of each element, with the option to have none or many? If so, could you please guide me in the right direction. <header> <nav> <ul> <a href="http://localhost:4000 ...

Is it common practice to provide a callback function as a parameter for an asynchronous function and then wrap it again?

app.js import test from "./asyncTest"; test().then((result)=>{ //handle my result }); asyncTest.js const test = async cb => { let data = await otherPromise(); let debounce = _.debounce(() => { fetch("https://jsonplaceholde ...

What is the process for eliminating the hover effect on a Bootstrap button?

I have customized a Bootstrap button in my stylesheet to make it dark, but it still has a hover effect from Bootstrap that I want to remove. How can I get rid of this hover effect? Take a look at the code snippet below for reference: .btn-dark { min-w ...

Problem with organizing data by dates

My timers list looks like this: timer 1 => { startDate = 17/01/2019 11PM, endDate = 18/01/2019 9AM } timer 2 => { startDate = 18/01/2019 7AM, endDate = 18/01/2019 1PM } timer 3 => { startDate = 18/01/2019 12PM, endDate = 18/01/2019 10PM } time ...

Ways to avoid Next.js from creating a singleton class/object multiple times

I developed a unique analytics tool that looks like this: class Analytics { data: Record<string, IData>; constructor() { this.data = {}; } setPaths(identifier: string) { if (!this.data[identifier]) this.da ...

Tips on assigning html actions/variables to a flask submit button

I am facing an issue with my Flask app where the form submission process takes a while for the backend to process. In order to prevent users from refreshing or resubmitting, I want to display a loading gif during this time. The current HTML code for my fl ...

Ways to conceal a dynamically generated div upon page load?

I am currently facing a scenario where I need to dynamically create a div. My initial approach was to create it on the document ready event, but the requirement is for it to be displayed only upon selection. The problem I am encountering is that the empty ...

Error Encountered in Laravel 5.2 FormBuilder.php

Encountering Laravel 5.2 ErrorException in FormBuilder.php on line 1235 stating that the method 'style' does not exist. This error has me perplexed. I have already made updates to my composer.json file by adding "laravelcollective/html": "^5.2" ...

Don't forget to save the selected date in the datepicker

I have a datepicker with two text fields: fromdate and todate. When I input the month of May and submit, then input another date, the default date should remain as May, instead of changing to the current month. Check out my code below. $(function() { ...

Implementing real-time streaming communication between server and client with Node.js Express

When a post request is made, the server generates data every few seconds, ranging from 1000 to 10000 entries. Currently, I am saving this data into a CSV file using createWriteStream and it works well. How can I pass this real-time (Name and Age) data to t ...

Dynamic anime-js hover animation flickering at high speeds

I have implemented the anime-js animation library to create an effect where a div grows when hovered over and shrinks when moving the mouse away. You can find the documentation for this library here: The animation works perfectly if you move slowly, allow ...

Parameterized function call on click event

There is a function defined as follows: menu[0].onclick = function() { filters.reset_all(); clients.get(); } This function gets called when the user clicks on the first menu element. Now, I need to invoke this function from another place and here ...

Is it possible to display partial html templates by accessing the local url and blending them with the main index.html file?

Is there a way to view partial HTML templates locally without copying them into the main index.html file? I'm looking for a solution that allows me to access my partial templates through a local URL without having to manually paste them into the main ...

Scrolling glitch detected on the Telegram web application

Currently, I am working on building an app with Bubble.io that will be used in the Telegram webapp. However, when I pull down (scrolling up) at the top of the page, Telegram interprets it as a close gesture and attempts to minimize the app window. I would ...

Subscriber client successfully activated and operational via the command line interface

I have incorporated a script into my PHP file that reads the Pusher channel and performs various actions when a new event occurs on the specified channel. If I access the following URL in my browser: http:/localhost/pusher.php and keep it open, the p ...

Filtering an array of objects by multiple arrays of keys

My data set consists of an array of objects const Data = [ {first_name: 'Ammy', city_name: 'LA', age: 22, designation: 'officer'}, {first_name: 'Dave', city_name: 'Paris', age: 23, designation: 'en ...

Locate the positions of 2 identification numbers within a Mongoose array

I am currently working on developing a middleware that validates if a conversation exists between two users in the database. If the conversation does not exist, the middleware will create a new conversation. I am attempting to utilize Mongoose's $in o ...

Utilize an AngularJS controller to verify the presence of a cookie and display a modal pop-up

In the process of developing a Single Page Application (SPA), I have encountered an issue with an HTML element calling an AngularJS controller. Here is what I need: I want the controller to check for a specific cookie: - If the cookie exists, call a ...

What could explain why the event listener functions properly on the initial call but fails on subsequent calls?

Currently, I am working on a bootstrap carousel where the "Previous" button is hidden on the first slide and the "Next" button is hidden on the last slide. Now, I want to disable the next button on the second slide (and eventually all slides with iframe vi ...