The extracted text from the window appears to be blank

When attempting to enclose a selected string between two characters, I am encountering an issue. For example, when selecting 'test' and clicking on the change button, the selected text should change to 'atestb'. However, although I am able to replace the selected text, window.getSelection().toString() is returning empty. Below is the function I am currently using:


replaceSelectedText(startTag, endTag) {
    let sel, range;
    console.log(window.getSelection().toString())
    if (window.getSelection) {
        sel = window.getSelection();
        if (sel.rangeCount) {
            range = sel.getRangeAt(0);
            range.deleteContents();
            const selectedContent = sel.toString();
            console.log("Selected Content ")
            console.log(selectedContent)
            let replaceDiv = startTag + selectedContent;
            replaceDiv=endTag ? replaceDiv + endTag : replaceDiv;
            range.insertNode(document.createTextNode(replaceDiv));
        }
    } else if ((document as any).selection && (document as any).selection.createRange) {
        range = (document as any).selection.createRange();
        range.text = startTag;
    }
}

Link to Stackblitz https://stackblitz.com/edit/angular-idyhj5?file=src%2Fapp%2Fapp.component.ts

Answer №1

The issue lies in deleting the value before retrieving it.

range.deleteContents();
const selectedContent = sel.toString();

To resolve this problem, simply switch the order of these two lines so you store the contents before deleting them.

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

What is the best way to fill a list-group using JavaScript?

Fetching ticket data from a controller is done using the code snippet below: $.ajax({ type: "GET", url: "/Tickets/List/", data: param = "", contentType: "application/ ...

Customize the icon used for expanding and collapsing in AngularJS

I want to modify the icon (e.g., plus, minus) when clicking on an expand-collapse accordion. Currently, I am using the Font Awesome class for icons. While I know it can be easily achieved with jQuery, I'm wondering if there is a way to do this in Angu ...

how to change class on vue function result

I need a way to display the content stored in requestData as li elements. Each list item should have an onclick function that, when clicked (selected), adds a specific value from a reference to an array. If clicked again (unselected), it should remove the ...

Use jquery ajax to upload an image with a reusable input field

UPDATE: Progress has been made in solving this issue. Please refer to Jquery form no submission to IE7 and IE8. The main task remaining is sorting out the compatibility with IE7 and IE8. I have been utilizing THIS plugin to upload files as email attachmen ...

Ways to identify when a file download has finished with the help of javascript

let pageUrl = "GPGeneration_Credit.ashx?UniqueID=" + __uniqueId + "&supplierID=" + supplierID + "&CreditID=" + OrderIds; window.open(pageUrl); // Want to check if the file download is complete and then refresh the page location.r ...

The Vue JS Option element requires the "selected" attribute to be utilized as a property instead

I'm attempting to automatically have an option selected if the "selected" property is present on the option object. Here is my code snippet: <template> <select v-model="model" :placeholder="placeholder"> <option v-for="opt ...

Issue with Angular FormControl Pattern Validator failing to validate against regex pattern

My goal is to restrict a text input field to specific characters only. I am looking to allow: alphanumeric characters (a-z A-Z 0-9) 3 special characters (comma, dash, single quotation mark) : , - ' A few accented characters: à â ç è é ê î ô ...

Reorganize external dependencies in the wwwroot directory using gulp

In my development setup using VS 2015, ASP.net vnext, Angular 2, Typescript, and gulp.js, I have successfully automated the process of moving my scripts/**/*.ts files to the wwwroot/app folder. Now, I am looking to extend this automation to include my libr ...

Position the buttons in the react children's application

**Looking for help on positioning Black Widow in the center-left and Hulk at the bottom left of the screen. I'm having trouble figuring it out, does anyone have any tips? Also, I only want to isolate the buttons to each picture. Not sure if I need to ...

Data is not displaying correctly in the Angular Material Table

I'm currently trying to build a mat table based on an online tutorial, but I'm facing a problem where the table appears empty even though I have hard coded data. As someone new to Angular and HTML/CSS, I'm struggling to understand why the ma ...

Utilizing Conditional Statements in the @artsy/fresnel Framework

I recently started working on a responsive React application using the @artsy/fresnel npm package. Below is a snippet of the code I have implemented: <Media greaterThanOrEqual='computer'> <div style={{ padding: '20px 50px' ...

Having trouble successfully deploying the app generated by "dotnet new angular" onto Azure

After creating an app using the dotnet new angular template and running dotnet run, everything seemed to be working smoothly. However, when I pushed the code to GitHub and set up continuous deployment in Azure, the build process failed. I turned on Devel ...

Navigating through parent folder HTML files from child folder HTML files

Seeking guidance as I embark on a new project! Check out this link to see my skills in action: collegewebsite.zip Now for the query at hand. I am working on a project named Coffee Cafe for my tuition assignment. It involves utilizing CSS and HTML with J ...

Design a logo to serve as the main button on the navigation bar of the

I've been experimenting with adding a logo instead of the 'Home' text in my navigation bar, but I'm not sure where to implement it. Should I add it within #nav or separately? Also, I want the nav bar to stay fixed without overlapping on ...

Is sending an AJAX request to a Node.js Express application possible?

Currently, I am attempting to authenticate before utilizing ajax to add data into a database $('#button').click(function () { $.post('/db/', { stuff: { "foo" : "bar"} }, callback, "json"); }); Below is my node.js code: ...

In JavaScript, generate a new column when the text exceeds the height of a div

Is it possible to create a multicolumn layout in HTML that flows from left to right, rather than top to bottom? I am looking to define the height and width of each text column div, so that when the text overflows the box, a new column is automatically ge ...

What is the best way to deactivate the first two columns of the header in Vue?

I am attempting to deactivate the draggable function for the first 2 columns. I have tried using options in the draggable plugin. :options="{disabled : 'Subject'}" However, this disables the draggable functionality for all headers. < ...

Create a versatile multi-autocomplete-chips input in Angular 9 using FormArray and encounter the issue: ERROR TypeError: control.registerOnChange is not a

Current Situation Table component - a table with buttons to create or edit rows. Clicking on any of these buttons will open the same Dialog component containing an input field. The input field is a reusable multi-autocomplete-chips component. If the user ...

Utilizing a component from a different module

Currently working on Angular 4 and facing an issue with referencing a component from another module. In my EngagementModule, the setup is defined as below: import { NgModule } from '@angular/core'; // other imports... @NgModule({ imports: [ ...

What is causing the 'transitionend' event to trigger multiple times?

Currently, I'm honing my JavaScript skills by taking on the 30 days of JavaScript challenge. I'm puzzled by why the 'transitioned' event is triggered twice in the code snippet below. My CSS only contains one property called transform, ...