Is there a way to retrieve the current font size of highlighted text using JavaScript?

Currently, I am utilizing contenteditable on a div and am eager to include a button that will increase the font size of selected text.

By "selected text," I mean any text highlighted by the cursor.

To execute

document.execCommand('fontsize', false, size);
I must be able to determine the font size of the selected text in order to increment it by 1. How can I retrieve the font size of the currently selected text?

I experimented with the following:

var size = document.getSelection().fontSize.toString();
but unfortunately, it did not work as expected. Additionally, I attempted
document.execCommand('increaseFontSize', true, 1)
expecting it to increase the text size by one unit, yet nothing happened - no error message was displayed either.

This is another approach I tried:

var el = document.getSelection();

var size = window.getComputedStyle(el, null).getPropertyValue('font-size');

However, this resulted in the following error:

Failed to execute 'getComputedStyle' on 'Window': parameter 1 is not of type 'Element'

Answer №1

To find out the font-size of the parent element, you can use this method:

const selection = Window.getSelection();
if (selection) { // Verify that nothing is selected to avoid errors
  const size = window.getComputedStyle(selection.anchorNode.parentElement, null).getPropertyValue('font-size');
}

The Window.getSelection() function retrieves a Selection object. This object includes the property anchorNode, which points to the textNode that the selection belongs to. Through this, accessing the parentElement and retrieving the font size becomes straightforward.

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

How can I update an image source using JavaScript in a Django project?

Is it possible to dynamically change the image src using onclick without relying on hard paths or Django template tags? I have concerns that this may not be best practice. How can I implement a method to inject/change the ""{% static 'indv_proj&b ...

As the user types, automatically format the input field for a seamless and intuitive experience

My current application is running on Angular 1.3.10 I have implemented a jQuery function to automatically add a backslash to the expiration input field once the user types the third number. Although it was a quick fix, I now aim to move this functionality ...

Delete class at waypoints

I am currently using waypoints.js to manage a single-page website that includes a highlighted navigation feature. When the viewport reaches the element with the class "content", the corresponding navigation point is given the class "active". The script i ...

Unable to add MySQL results to the array

This is the code I am working on: var nbu = req.body.nbu; var inv=[]; db.query( "SELECT * FROM `invoice_ska` WHERE nm_client =?", nbu, (err, results) => { if (err) throw err; inv.push(results); } ); console.log(inv);//this just [] }); I ...

Angular is capable of transferring data from a form using the [POST] method

I need assistance with: var body = {username:"ali", password:"p"}; this.http.post('http://localhost:27017/user/auth', body).subscribe(data => {console.log(data);}); Is there a way to populate the 'body' variable using form dat ...

Tips for creating a loading page that displays while your website loads in the background

Is there a way to display a loading animation or image while my website is loading in the background? I've noticed that it takes about a minute for my website to fully load. I attempted to use <meta http-equiv="refresh" content="1000 ...

Troubleshooting a JavaScript Script Issue in a NextJs Class

I have been working on my website and decided to incorporate an FAQ page. I used a template for the FAQ section and tried to implement Javascript in my NextJs project, but unfortunately, it's not functioning as expected. var faq = document.getEle ...

How to extract the text before a question mark using JavaScript regex if it exists

I'm dealing with a situation where I have strings like #test or #test?params=something var regExp = /(^.*)?\?/; var matches = regExp.exec($(this).data('target')); var target = matches[1]; console.log(target); I always want to extract ...

unable to send array in cookie through express isn't functioning

Currently, I am in the midst of a project that requires me to provide the user with an array. To achieve this, I have been attempting to utilize the res.cookie() function. However, each time I try to pass an array as cookie data, the browser interprets it ...

Unable to retrieve Vue resource within Vuex action

Hello everyone, I'm currently facing an issue while trying to make a request within my action on the Vuex side, and I keep getting this error: Cannot read property '$http' of undefined I have configured my vue-resource in the following man ...

Changing the background color of a button in AngularJS as the input value gets updated

Currently, the page is in the process of creating an account. I am looking to change the button background color to gray when one of the inputs does not have a value. Conversely, when all inputs have a value, I want the button background color to be blue. ...

React - Survey.js... Users are reporting issues with the functionality of the EDIT button for survey items

Having trouble integrating Survey.js into my React application. I am able to load the Survey Editor interface initially, but I am encountering issues when trying to edit the questions. The "EDIT" and "..." buttons are unresponsive, triggering an error as d ...

Messages and responses from an array within a discord.js bot

Currently, I am attempting to set up my discord.js version 12.0.0 bot to react to specific words using arrays for words and corresponding responses. However, I am encountering the following error message: TypeError: Cannot read property 'split' o ...

Utilizing asynchronous false in Wordpress Ajax functionality

Is there a way to use the AJAX return value outside the function in WordPress? For example: function get_login_member($) { $.post(ajax_object.ajax_url, {action: 'getloginmember'}, function (data) { data = JSON.parse(data); ...

What is the best way to import the three.js OBJLoader library into a Nuxt.js project without encountering the error message "Cannot use import statement outside a module

Beginner here, seeking assistance. Operating System: Windows 10. Browser: Chrome. Framework: Nuxt with default configurations I have successfully installed three.js using npm (via gitbash) by running npm install three --save. It is included in the packag ...

Ways to identify when an HTMLElement's size changes due to a percentage-based width setting

Currently, I am in the process of developing an Angular Component and have implemented the following CSS code: :host { display: block; width: 100%; } The main objective here is to ensure that the component remains as responsive as possible. However, ...

Should I keep my Mobx stores in a dedicated file or include them directly in the React component?

There are a couple of ways to define observable properties and actions in MobX. One way is to include them directly in the component like this: // App.js class App extends Component { @observable a = 'something' @action change() { this. ...

Tips for resolving issues with mat-autocomplete during scrolling

When I open the mat-autocomplete and scroll down the page, I would like for the mat-autocomplete to stay in place. ...

Tips for storing an array of strings in a JSON file using Javascript

Is it possible to save an array of strings to a JSON file using Node.js? const alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']; example.json [ "a", "b&q ...

Explore all sorts of data such as search term within a JavaScript JSON array

In my JSON array of objects, I have data displayed in an HTML table. Above the table, there is a search input where users can enter search terms. [ { "id": 1, "title": "My fridge door closed", "description": "The fridge door was closed yesterday.", "point ...