Execcommand() is now obsolete, what's the alternative?
To replace document.execCommand()
, use classList
or style
for text styling and the Clipboard API
for clipboard operations.
Text styling example:
Clipboard action example:
Given the obsolescence of document.execCommand()
, no perfect "one-size-fits-all" alternative exists. However, specific modern web APIs can serve some of the same functionalities depending on the use-case.
Navigating browser diversity and IME nuances
Despite being obsolete, document.execCommand()
still enjoys cross-browser compatibility. This wide support still guarantees its utility, especially when dealing with IME input and caret movement across diverse environments.
Even in an obsoleted state, execCommand()
is needed to deal with many IME nuisances. Proper IME input is crucial to maintain functionalities, like typing and word suggestions on mobile keypads, such as Android's GBoard.
Crafting custom WYSIWYG editors
Replacing execCommand()
while building a custom WYSIWYG editor involves many APIs, such as Input Events Level 2 and .cloneNode
method, complemented by cautious usage of semantic HTML tags like <em>
, <strong>
rather than <span>
and rigorous cross-browser testing, especially for Gecko-based browsers.
Code hints for modern APIs
Check out the following examples to see how you can implement modern API alternatives:
- Use
navigator.clipboard.writeText()
for text copying andnavigator.clipboard.readText()
for pasting, usingClipboard API
. - Achieve rich text editing using
document.createRange()
andRange.surroundContents()
techniques. - Utilize powerful DOM manipulations with methods like
insertBefore()
andreplaceChild()
.
These replacements facilitate cleaner scriptwriting and adherence to modern web standards.
Creating accessible web functionalities
As a developer, prioritize accessibility. Ensure manipulations to the DOM are communicated to screen readers and other assistive technologies effectively.
Visualising the shift in web APIs
Comparing old and new tools for web text manipulation:
Each tool in the new toolset specializes in a particular function.
Continuing with persistent frameworks
Creating a custom editor requires persistence and preparedness to navigate complexity. The use of frameworks can both aid and potentially obstruct maintainability. Stay updated on new standards and test across various platforms to avoid hidden browser quirks.
Was this article helpful?