Can JQuery be used to identify the CSS styles applied to selected elements?

Highlight the text by selecting it and clicking a button. If the text is already highlighted, clicking the button should make the selected text return to normal.

Can this be achieved using jQuery and a single button?

Is it possible to identify the CSS style applied to the selected text?

Answer №2

This question has already been addressed in this particular post.

function enableEditingAndHighlight(color) {
    var textRange, selection = window.getSelection();
    if (selection.rangeCount && selection.getRangeAt) {
        textRange = selection.getRangeAt(0);
    }
    document.designMode = "on";
    if (textRange) {
        selection.removeAllRanges();
        selection.addRange(textRange);
    }
    // Using HiliteColor as BackColor may affect the entire block in some browsers
    if (!document.execCommand("HiliteColor", false, color)) {
        document.execCommand("BackColor", false, color);
    }
    document.designMode = "off";
}

function highlightSelectedText(color) {
    var textRange, selection;
    if (window.getSelection) {
        // For IE9 and other browsers
        try {
            if (!document.execCommand("BackColor", false, color)) {
                enableEditingAndHighlight(color);
            }
        } catch (exception) {
            enableEditingAndHighlight(color)
        }
    } else if (document.selection && document.selection.createRange) {
        // For IE 8 and earlier versions
        textRange = document.selection.createRange();
        textRange.execCommand("BackColor", false, color);
    }
}

document.getElementsByTagName('button')[0].addEventListener('click', function(){
highlightSelectedText('red');
});
<div>
  <p>
    Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr.
  </p>
  <button>Change color</button>
</div>

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

Display personalized error messages using jQuery and PHP

I implemented an Ajax autocomplete feature on an input field within a form using jQuery. Here are the ajax settings I have set up: $.ajax({ type: "POST", url: myUrl, data: $("#id__form").serialize(), success: function(data){ ...

When working with JavaScript, the `textarea` value property will not recognize line breaks or white spaces when being read

Recently, I've been developing a browser-based notebook app. However, I encountered an issue where if I type a note like this: *hello this is my first note The app displays it as: hello this is my first note Additionally, I want elements with the ...

Adding content in real-time at the current cursor position within a Contenteditable element using Angular

I have a contenteditable div where I am facing an issue with pasting text. Whenever I try to paste some text into the div, it always gets pasted at the end. I am using ViewChild to access the reference of the contenteditable div and utilizing innerText to ...

Anchored text is obscured by a fixed Bootstrap 4 navigation bar at the top

I'm currently developing a website that utilizes bootstrap 4. I have successfully fixed the <nav> element to the top of the page using the fixed-top class. Despite applying padding-top to the <body> tag as recommended, I am encountering an ...

Is it possible to maintain variables across a session with numerous users when utilizing socket.io?

My code structure is designed as follows: //Route Handler that triggers when a user 'creates a session' app.post('/route', async (req, res) => { let var1 = []; let var2 = []; io.on('connection', (socket) => ...

Count in JavaScript that picks up where it left off

I'm working on setting up a countdown timer that runs for 24 hours, showing the days, hours, minutes, and seconds. The challenge I'm facing is how to save the progress of the countdown. Essentially, I want it to resume from where it left off for ...

Javascript problem involving multiple scopes in closures

What is the most effective solution for addressing this issue related to closure in JavaScript? Here is a simple problem I am facing: I have 10 spans with onclick events (I want an alert showing the number of the span clicked on each click): var spans = ...

Struggling to retrieve information from a PHP page using AJAX?

I am facing an issue with my HTML form and AJAX code. I have used AJAX to send the ID of the clicked button to a PHP page, but it seems that the PHP page is receiving a null value instead of the expected ID. As a beginner who has learned through tutorials, ...

PHP not receiving values when making an AJAX POST request

My AJAX file below is where I pass all the values from my text boxes and post them to edu.php. In edu.php, I intend to update two tables - details and test. However, nothing seems to be updating in my database. When I checked the values with var_dump, the ...

Finding dynamic elements with Selenium WebDriver is an essential skill for any automation tester

<div id="button" data-testid="widgetButton" class=" chat-closed mobile-size__large"> It seems there is an issue with locating elements that have special characters in their names. I'm attempting to click on a specific item, but I've tried ...

Issues with displaying form/button glyphicon when using a fixed table header in Bootstrap

I have a situation where I have a table with a fixed header. In one of the columns, there are delete buttons within a form. The table structure is as follows: <div class="panel panel-default table-responsive fixedHeader"> <!-- Table --> &l ...

What is the method of adding a child to the outerHTML of the parent element instead of within it?

Is there a way to use the outerHTML method on a parent element to append a child element so that the icons appear outside of the targeted element rather than inside it? The current code snippet shows the icons inside the box, but I want them to be placed o ...

Comparing the syntax of JSON to the switch statement in JavaScript

I recently came across a fascinating post on discussing an innovative approach to utilizing switch statements in JavaScript. Below, I've included a code snippet that demonstrates this alternative method. However, I'm puzzled as to why the alter ...

The retrieved item has not been linked to the React state

After successfully fetching data on an object, I am attempting to assign it to the state variable movie. However, when I log it to the console, it shows as undefined. import React, {useState, useEffect} from "react"; import Topbar from '../H ...

Styling buttons with different colors using React onClick event.getSelectedItem() method

I am having an issue with adding a border when the class is set to "transportation active" in my React code. When I click on one of the icons, all of them become active instead of just the clicked one. This behavior is not what I want, as I only want the ...

Choose all elements following the first child element

My goal is to create a LESS rule that targets every element following the current element, excluding the first child. I've tried using this syntax: (& ~ *):not(:first-child) { margin-left: 5px; } and also this one: & ~ *:not(:first-child ...

Using jQuery, organize tables by the value of their td class

, I am attempting to organize various td elements within one or more trs based on their respective classes. These are all housed in multiple table elements with the classname "hosts". Currently, my jQuery abilities are lackluster and I am struggling to sor ...

"Concealing children elements disrupts the functionality of the CSS grid layout

Is there a way to prevent layout issues when using CSS to dynamically display items? For example, when hiding button A it causes the Edit button to shift to the left instead of sticking to the right edge of the grid as expected. <html> <body> ...

Transforming the output of a PHP script from an HTML table into an ion-list format tailored for the Ionic framework

Currently I am working on an application built with the Ionic framework. I have developed a PHP file to retrieve 'Users' data from my database and it is currently being displayed in an HTML table format. In the services section of the framework, ...

Preventing Data Duplicates When Inserting in ASP.NET MVC

I have noticed that when sending an insert query to my Oracle database through MVC ACTION, the insert method seems to be called twice and records the same data twice... Furthermore, when using the same structure to run a select query, I am getting the sam ...