1

I am using contentededitable on a div and want to add an increase font size button for selected text.

Selected text meaning highlighted with the cursor.

In order to run document.execCommand('fontsize', false, size); I need to know the size of the selected text, so I can increase it by 1. How do I get the font size of the currently selected text?

I tried: var size = document.getSelection().fontSize.toString(); but that was no bueno. I also tried document.execCommand('increaseFontSize', true, 1) assuming it would increase it by one integer, but nothing happens, not even an error.

I tried this:

var el = document.getSelection();

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

But I get the error Failed to execute 'getComputedStyle' on 'Window': parameter 1 is not of type 'Element'

ballyehove
  • 61
  • 5

1 Answers1

4

You can determine the font-size of the parent element like this:

const selection = Window.getSelection();
if (selection) { // make sure it doesn't error if nothing is selected
  const size = window.getComputedStyle(selection.anchorNode.parentElement, null).getPropertyValue('font-size');
}

Window.getSelection() returns a Selection object. On those objects, the property anchorNode contains a reference to the textNode that selection is part of. That, in turn, has the usual parentElement property. From there it's easy.

connexo
  • 53,704
  • 14
  • 91
  • 128