Here is a better solution than many proposed here, as it directly gets the element on which to change the font size from the selected text.
As a consequence, it doesn't have to browse the DOM to get the right element, and doesn't require to ban the use of a specific fontSize (7, as suggested in the first option of the accepted answer, and in other answers).
function changeFont() {
document.execCommand("fontSize", false, "7");
var fontElements = window.getSelection().anchorNode.parentNode
fontElements.removeAttribute("size");
fontElements.style.fontSize = "30px";
}
In summary we just use execCommand to wrap the selection with a span, so that the subsequent call to getSelection() whill have the highlighted span as parent . Then we just add the fontSize style to that identified span.
Here, as we are using the fontSize command, it won't be wrapped inside a <span>
, but inside a <font>
.
But this is a generic method which can work with any command of execCommand, the latter being used just as a convenient manner to wrap the selected contents even among different elements.
Here is a live DEMO