How to access selection range styles using JavaScript

It is common knowledge that we can retrieve the selection of text in JavaScript using the following method:

var range = window.getSelection ();

However, how can we obtain the style of this selection? For example, when I select bolded text or italicized text, how can I determine their styles?

(One idea I have is to get the position of the selected text and retrieve the HTML at that specific position...)

Answer №1

Utilize the document.queryCommandState() method for checking if text is in bold or italic, and use document.queryCommandValue() to determine font size and style.

Remember to provide a flag to each method in order to receive a true or false value, as it will not automatically return the current styles. For example, to check if selected text is bold, you can write...

if(document.queryCommandState('Bold')){
  // it's bold!
}

This information provides a range of identifiers and methods.

Explore more at this link

Answer №2

If you're looking to determine the status of formatting commands like "Bold" and "Italic" that don't have a value, you can utilize document.queryCommandState() (check out dottoro). For commands that do have a value, such as "FontName," consider using document.queryCommandValue() (also see dottoro).

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

Navigating through nested promises can be a daunting task within the world of JavaScript and Angular

Function 2 relies on the return of Function 1, while Function 3 uses both returns. How can I clean up this process? Currently, Function 3 is only giving me undefined values. Below are my 3 functions: Function1 $scope.nombreCompetencesATraiter = function ...

What steps can be taken to avoid including empty tasks in React code?

Is there a way to prevent my application from adding empty tasks? Below is the code snippet for adding a new task to an array. How can I implement a condition to block the addition of empty tasks? This application follows Mozilla's guidelines for a R ...

Creating an array of objects sorted in alphabetical order

My task involves working with an array of objects that each have a name property: var myList = [{ name: 'Apple' }, { name: 'Nervousness', }, { name: 'Dry' }, { name: 'Assign' }, { name: 'Date' }] ...

AngularJS is not immediately responsive to changes in $window.document.visibilityState

I am currently working with AngularJs version 1.4 and I need to be able to detect when a user is not on the tab of my app and when they return. To achieve this, I attempted using $watch in the following way: $rootScope.$watch(angular.bind($window, functio ...

Struggling to pinpoint the exact element in Python/Selenium

As I work on creating a website manipulation script to automate the process of email mailbox creation on our hosted provider, I find myself navigating new territory in Python and web scripting. If something seems off or subpar in my script, it's beca ...

Creating a dynamic multi-series line chart in D3 version 4 that incorporates data points with matching colors to their respective lines

In my attempt to enhance a multi-series line chart with D3 V4 in Angular-cli, I have encountered a challenge. Below is the code snippet of what I have been working on. var lookBookData = z.domain().map(function (name) { return { name: name, ...

The font in my Next.js / Tailwind CSS project starts off bold, but unexpectedly switches back to its original style

I recently integrated the Raleway font into my minimalist Next.js application with Tailwind CSS. I downloaded the font family in .ttf format and converted it to .woff2, but I'm having trouble changing the font weight using custom classes like font-bol ...

Issue Arising During File Transfer in Nativescript

I am currently attempting to upload an image that I captured with Nativescript to a server using a web API that I created in C# (ASP.NET). The API works perfectly fine when tested on Postman, but I encounter an error "Error During Upload" while trying to u ...

Changing the color of a div element dynamically with JavaScript

Is there a way to improve the code below so that the background color of this div box changes instantly when clicked, without needing to click twice? function updateBackgroundColor(platz_id) { if(document.getElementById(platz_id).style.backgroundCol ...

Local email.js functionality successful, but fails upon deployment alongside React

I have implemented Email.js to create a contact form for a Next.js website. It functions perfectly when tested locally, but encounters issues once deployed. Upon clicking the submit button, the form fails to reset as intended within the sendEmail function. ...

How can I reference a function in a single file component using Vue.js?

Within my Vue.js project, I have crafted a single file component known as Password.vue which comprises two password fields along with their associated validation checks. To begin with, I structure my HTML within the <template></template> tags, ...

Update an existing item or add a new one if it is not already present

I am attempting to create a functionality similar to canva.com, where users can select images from the sidebar and drop them anywhere in the "div", allowing multiple images with individual positions. However, when I use setState(prevState=>{return [...p ...

Having trouble with string matching in JavaScript?

My attempts to verify my Ajax response with a string have consistently resulted in a fail case being printed. Below is the section of code relating to my ajax request: var username = document.getElementById("name").value; var password = document.getEle ...

How should filtering be properly done on a data array within a Redux reducer function?

I am trying to develop a function that filters an array based on a search input. The goal is for the filter action to trigger when there's a change in the SEARCH_TEXT. However, I'm facing confusion when it comes to handling the state when the del ...

Dynamic Dropdown Menu in Zend Framework with Autofill Feature

I've been diligently working on a code to automatically populate dropdowns onchange, right after selecting the necessary values from an autocomplete search field. However, I am facing an issue where my autofill feature fails to work after making a sel ...

URL from different domains

Currently, I am attempting to utilize this URL within my javascript code: Below is the snippet of my javascript code: $.ajax({ url: 'http://api.addressify.com.au/address/autoComplete', type: 'GET', crossDomain ...

Learn how to collapse a collapsible section in Jquery Mobile by clicking on a link. Check out the example on JSFiddle

Is there a way to make the data-role collapsible collapse when clicking a tab link? I've tried using an on-click function without success. Any ideas or alternative solutions? Thanks. Check out my JSFiddle, where you can see that the tabs change but t ...

Express landing page continuously serves static files

I'm facing an issue with using static files in my project. When a user makes a get request to the "/" landing page, I intend to send non-static data like a JSON response. However, instead of sending "123", it automatically serves my index.html file fr ...

Do I have to include reject() in the executor when using promises in express.js?

If we choose not to handle rejection, is it necessary to include the reject parameter in the promise executor? For example: new Promise((res) => { res(a); }) ...

The combination of AddEventListener in the parent and postMessage in the iframe is ineffective

As I delve into the Stripe documentation to develop a new feature, I have encountered an issue regarding the communication between a webpage and an iframe. The code in index.html: <!DOCTYPE html> <body> parent<br> <iframe src="./ ...