Changing the text color of a selected text in HTML

I have a feature to change the color of selected text using Javascript. Here is the method I am currently using:

function marking_text(replacrmenthtml){
    try {
        if (window.getSelection) {
            sel = window.getSelection();
            var range = sel.getRangeAt(0);

            var selectionStart = $("<span style=\"color:red\">");
            var startRange = document.createRange();
            startRange.setStart(range.startContainer, range.startOffset);


            var selectionEnd = $("</span>");
            var endRange = document.createRange();
            endRange.setStart(range.endContainer, range.endOffset);

            startRange.insertNode(selectionStart[0]);
            endRange.insertNode(selectionEnd[0]);
        }
    }
    catch (e) {

    }
}

However, when calling this method, it encounters a DOM exception. It seems that inserting the starting span tag before the selected text causes disruption in the DOM structure without an end tag present. How can this issue be resolved?

Edited: There will be a highlight button. When the user selects text and clicks on the highlight button, the color of the selected text will change.

Answer №1

For those situations where you need to alter the color upon selection, add the following code snippet.

    ::-moz-selection { color: red;}
    ::selection { color: red; }

Answer №2

While this question pertains to JS, there is a nifty CSS selector that can achieve the desired effect.

::selection {
  color: blue;
}

If the browser deems your choice inaccessible, it may override your selected colors. This technique works best with colors and background colors for styling purposes.

For further reading:

Answer №3

The CSS Custom Highlight API, https://developer.mozilla.org/en-US/docs/Web/API/CSS_Custom_Highlight_API, provides a convenient way to mark specific text ranges with custom highlight styles in JavaScript. By defining the highlight style in CSS, you can create persistent highlighting effects that resemble text selection.

For instance:

<style>
  div::highlight(bar) {
    background-color: orange;
  }
</style>
<div id="highlighted">This text is customized highlighted</div>
<script>
  let range = new Range();
  range.setStart(highlighted, 0);
  range.setEnd(highlighted, 1);
  let customHighlight = new Highlight(range);
  CSS.highlights.set('bar', customHighlight);
</script>

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

Can someone explain the process of unescaping characters in an API response to me?

I have created an application that leverages AngularJS to pull data from the WP Rest API V2. The response includes escaped characters, like the example below: "excerpt": { "rendered": "<p>When we go shopping, we encounter many different labeling ...

Steps for implementing a dynamic animation within a table cell when the value is updated

Incorporating vuetify and nuxt into my web application, how can I implement an animation on a cell when its value changes? I attempted to attach a reference to my table element like so: <v-data-table ref="table" :items="data" :hea ...

Hiding the author, category, and date information from displaying on WordPress posts

After creating a Wordpress blog site and adding the category widget to the right sidebar as a drop down, I realized that I needed to customize its layout in terms of colors and design. However, I am struggling to find out how it can be done, which .php fil ...

Answer for background picture when reducing magnification

Currently, I am facing the challenge of converting a PSD template to HTML. Specifically, I need guidance on how to handle the background food images (highlighted in red in the image) when zooming out the browser. The total width is 1300px with a container ...

What is the best way to choose a specific row with Enzyme?

We have chosen Jest for doing UI Test-Driven Development on our React application. Our component rendering structure looks like this: <Div> <Row> </Row> <ROW> <Row> <ROW> <Link> <Link> ...

Tips for aligning navigation bar items to the right side

Seeking help with positioning the logo on the left and navigation items on the right using Bootstrap classes, while maintaining responsiveness. Click here for sample image 1 Check out the navbar layout <!-- Logo --> <a class="nav ...

Having trouble getting numerical values from the computed transform matrix in Javascript? The result might be NaN

Recently, I've been working with the transform computed style property. matrix3d(1.5, -7, 2, 0, 7, 1.5, 0, 0, -3, 1, 1, 0, 100, 0, 0, 1) Now, my goal is to convert this into an array of numbers: var s = window.getComputedStyle(element); var mattrix ...

What is the best way to utilize AJAX for uploading .mp4, .mp3, and .doc files together with additional FormData?

Hello everyone, I have been successfully uploading files (documents and images) using AJAX. However, I am facing some challenges when it comes to uploading videos through AJAX. I have searched extensively on this site for solutions but have not found exact ...

Read a local file using the HTML5 FileReader

I am currently working on developing an offline application that can read text from a locally stored text file. I have been researching and found that using html5 and FileReader can make this possible. My goal is to set a hard-coded relative path for the ...

What is the default way to toggle content in rows using Material UI?

Currently, I am utilizing Muitables and have a query regarding how to set the expanded rows to be displayed by default, similar to the illustration below: Upon initial page load, it is preferred for the content in that row to automatically expand (arrow d ...

Guide on transferring JSON information from a client to a node.js server

Below is the code snippet from server.js var express = require("express"), http = require("http"), mongoose = require( "mongoose" ), app = express(); app.use(express.static(__dirname + "/client")); app.use(express.urlencoded()); mongoose.con ...

Angular JS throwing error: 'ngMessages' not initialized

Here is the code snippet I am working with: // LoginCtrl.js angular.module('homeon', [ 'ngMessages' ]).controller('loginCtrl', function($rootScope, $scope, $state, $ionicLoading, dbservices, server) { //------------ ...

Changing the text of a button using ngClass in Angular's toggle functionality

Is there a way to modify the text of a toggled button class in Angular using Bootstrap? Currently, I have this code to toggle the class: html <!-- toggle button --> <button type="button" class="btn btn-primary mt-3 ml-3" (click)="status=!status ...

Issue with React Testing Library: Attempting to access the 'contents' property of an undefined value in Redux

Hello, I'm new to writing test cases using React Testing Library. Below is the code of my component: import React from 'react'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; ...

"Unlock the power of Angular.js: Extracting table row data with the click of a checkbox

Can anyone help me with this? I am trying to retrieve all checked data from a table row using Angular.js. Below is my code: <tr ng-repeat="gl in galleryDatas"> <td><input type="checkbox" name=""> {{$index+1}}</td> <td><img ...

How can we efficiently loop through all the icons in React Material-UI?

I am looking to iterate over all the icons from @material-ui/icons in a React application. If I want to import a single icon, I can do so like this import IconNameIcon from '@material-ui/icons/IconName' and then use it in my component like th ...

Hide a parent div in jQuery depending on the checkbox status

I have a code snippet that I need help with. You can view the code here. $("#filters :checkbox").change(function() { $(".listing-details > div").hide(); $("#filters :checkbox:checked").each(function() { $(".listing-details ." + $(this). ...

Is there a way to verify if a variable is a generator function, for example, a function with the asterisk symbol and

Is there a foolproof method to determine if a function is a generator, like in the example below: let fn = function* () { yield 100; } if (fn instanceof ??) { for (let value in fn()) { ... } } I have only been able to come up with fn.to ...

Display a loading indicator while rendering several Vue components

My current challenge involves loading multiple Vuetify card components based on the selected category at the top of the page. The issue arises when the array renders more than 50 cards, causing a significant delay in loading time. While I am not overly co ...

Troubleshooting Issue with InfoWindow Display on Multiple Markers in Google Maps

I'm having trouble getting my markers to show different infowindows. No matter what I do, the markers always display the content of the last "contentString" in the loop. Despite reading through multiple posts on this issue, I haven't been able t ...