The document.execCommand() API has been deprecated and may stop working in future browser versions. Modern alternatives should be used instead.
Using the Selection API
Instead of execCommand('bold'), you can wrap the selected text in a <strong> element using the Selection and Range APIs.
function applyBold() {
const selection = window.getSelection();
if (selection.rangeCount === 0) return;
const range = selection.getRangeAt(0);
const strong = document.createElement('strong');
try {
strong.appendChild(range.extractContents());
range.insertNode(strong);
selection.removeAllRanges();
selection.addRange(range);
} catch (e) {
console.error('Failed to apply bold:', e);
}
} Using beforeinput event
The beforeinput event allows you to intercept and modify input before it's committed to the DOM. Browser support varies by version, so always test in your target browsers.
element.addEventListener('beforeinput', (e) => {
if (e.inputType === 'formatBold') {
e.preventDefault();
// Apply bold formatting using Selection API
applyBold();
}
}); Common operations
Bold, Italic, Underline
Wrap selected text in <strong>, <em>, or <u> elements using the Selection API.
Insert HTML
Instead of execCommand('insertHTML'), create DOM nodes and insert them at the selection position.
Delete content
Use range.deleteContents() to remove selected content programmatically.
Challenges
Complexity: The Selection API approach is more complex than execCommand and requires careful handling of edge cases (empty selections, collapsed ranges, etc.).
Browser differences: Selection and Range behavior varies across browsers, especially when dealing with complex DOM structures or IME composition.
No standard replacement: There is no single, standardized replacement for execCommand. Each operation must be implemented separately using the Selection API.