Frontend Rich Text Basics and Implementation
This article introduces the concept of rich text in the frontend, explains two primary input methods (iframe with designMode and contenteditable elements), details the Selection API for handling text ranges, demonstrates toolbar commands using execCommand, and provides complete demo code for building a simple rich‑text editor.
In daily life we encounter many document formats, and rich text plays an important role in them. For front‑end developers, rich‑text products are increasingly common. This article introduces basic concepts of front‑end rich text and simple implementation ideas.
What is Rich Text
Plain text contains only characters, while rich text (RTF) includes styles and formatting. Formats such as doc, docx, rtf, and pdf are examples of rich‑text files.
Rich Text in Front‑End
Front‑end rich text is realized by HTML elements combined with inline styles. Editors like TinyMCE, UEeditor, and Draft render semantic tags and inline styles to achieve rich‑text editing.
Rich‑Text Input Methods
Two common ways to enable editing are:
iframe
Insert an iframe into a blank HTML document and set its designMode attribute to on . The iframe’s body becomes editable, providing style isolation.
contenteditable
Set the contenteditable attribute on any element (e.g., a div ) to make it directly editable. This method may share page CSS and can be combined with autocapitalize and spellcheck for better UX.
Differences
Both methods enable editing with block‑level elements for line breaks. The iframe approach isolates styles, while contenteditable inherits page styles; developers can choose based on requirements.
Selection Object
The Selection object represents the user’s selected text range. It can be obtained via window.getSelection() and provides properties such as anchorNode , anchorOffset , focusNode , focusOffset , rangeCount , and type . These properties allow developers to determine the start and end of a selection, delete, replace, or insert content.
Selection Example
When the selection spans from the text node "政采云" (anchor) to "ZOO" (focus), the offsets indicate the exact character positions, and the type is Range . If anchor and focus are the same, the type is Caret .
Usage
Common operations include deleteFromDocument() to remove selected content and inserting new nodes via the range API.
const insert = () => {
window.getSelection().deleteFromDocument();
const { anchorNode, anchorOffset } = window.getSelection();
if (anchorNode.nodeType === 3) {
const str = anchorNode.nodeValue;
anchorNode.nodeValue = str.substring(0, anchorOffset) + '😄' + str.substring(anchorOffset);
} else {
const newNode = document.createElement('span');
newNode.innerText = '😄';
anchorNode.insertBefore(newNode, anchorNode.childNodes[anchorOffset]);
}
};Toolbar Implementation
After enabling input, the document.execCommand() method can apply formatting commands such as bold , italic , foreColor , and insertImage . The method signature is document.execCommand(commandName, showUI, value) . Common commands are listed in the table below.
Command
Effect
Value
bold
Toggle bold style
null
italic
Toggle italic style
null
foreColor
Change text color
color string
insertImage
Insert image at cursor
image URL
const bold = (val) => {
document.execCommand('StyleWithCSS', true, true);
document.execCommand('Bold', false, val);
};
const italic = (val) => {
document.execCommand('StyleWithCSS', true, true);
document.execCommand('italic', false, val);
};
const changeColor = (val = '#ff0000') => {
document.execCommand('StyleWithCSS', true, true);
document.execCommand('foreColor', false, val);
};
const insertImage = (val = 'https://example.com/image.png') => {
document.execCommand('StyleWithCSS', true, true);
document.execCommand('insertImage', false, val);
};Data Collection and Rendering
The editor’s innerHTML is the rich‑text data. It can be stored in a database and later set back to the container’s innerHTML to render the content.
Demo Code
The following complete HTML demonstrates both iframe‑based and contenteditable‑based editors with the toolbar functions above.
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Rich Text Demo</title>
<style>
.rt-container { height:200px; width:500px; padding:10px; overflow:auto; }
</style>
</head>
<body>
<button onclick="bold()">Bold</button>
<button onclick="italic()">Italic</button>
<button onclick="changeColor()">Change Color</button>
<button onclick="insertImage()">Insert Image</button>
<div class="rt-container" contenteditable="true">Editable Area</div>
<button onclick="boldIframe()">Iframe Bold</button>
<iframe class="rt-container" name="editor"></iframe>
<script>
window.addEventListener('load', () => {
frames["editor"].document.designMode = "on";
});
// toolbar functions defined here (bold, italic, changeColor, insertImage, boldIframe, insert, insert2)
</script>
</body>
</html>By following the concepts and code above, readers can build a simple front‑end rich‑text editor and extend it with additional features.
政采云技术
ZCY Technology Team (Zero), based in Hangzhou, is a growth-oriented team passionate about technology and craftsmanship. With around 500 members, we are building comprehensive engineering, project management, and talent development systems. We are committed to innovation and creating a cloud service ecosystem for government and enterprise procurement. We look forward to your joining us.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.