How can I change font size to 30px (for example) using document.execCommand
?
This:
document.execCommand(\"fontSize\", false, \"30px\");
Function
var execFontSize = function (size, unit) {
var spanString = $('<span/>', {
'text': document.getSelection()
}).css('font-size', size + unit).prop('outerHTML');
document.execCommand('insertHTML', false, spanString);
};
Execute
execFontSize(30, 'px');
Found a solution in pure JavaScript that works for multiple lines with custom HTML (colors, font families).
Get the selection of the document. Parse the selection and save the html tags from it. Then with document.execCommand insert the selected html inside a div that has inline style. Also a benefit when using document.execCommand('insertHTML', false, html) is that you get undo in WYSIWYG editor.
This is the function:
function fontSize(size) {
var sel = document.getSelection(); // Gets selection
var selectedHtml = "";
if (sel.rangeCount) {
var container = document.createElement("div");
for (var i = 0, len = sel.rangeCount; i < len; ++i) {
container.appendChild(sel.getRangeAt(i).cloneContents());
}
const children = container.getElementsByTagName("*")
for(let child of children) {
if(child.style.fontSize) {
child.style.fontSize = `${size}px`
}
}
selectedHtml = container.innerHTML;
}
let html = `<div style="font-size: ${size}px;">${selectedHtml}</div>`
document.execCommand('insertHTML', false, html);
}
Hope it helps.