Insert HTML at the current position of a contentEditable element
Written byPhuoc Nguyen
20 Sep, 2023
Level 1 — Basic
One real-life example of this is in a WYSIWYG editor. Let's say a user selects some text and clicks on the bold button. The editor can then insert
`<strong>`tags around the selected text at the current position. Another example is in chat apps where users can send formatted messages with links and images. By inserting HTML right where the user is typing, they can easily format their messages without having to type out all of the HTML tags by hand.
In this post, we'll explore various methods to accomplish that goal.
To add an element using the
`insertNode()`function, you can use the following code snippet as an example:
// Get the current selectionconst selection = window.getSelection();// Get the range of the current selectionconst range = selection.getRangeAt(0);// Create a new element to insertconst newElement = document.createElement('span');newElement.innerHTML = 'Hello, world!';// Insert the new element at the current positionrange.insertNode(newElement);
In this example, we grab the current selection and range of the selection. Then, we create a new
`span`element, set its inner HTML to
`Hello, world!`, and insert it at the current position using the
`insertNode`method of the range object.
Just keep in mind that this example assumes the contentEditable element is already in focus. Check out the live demo that showcases this approach in action! Don't forget to focus on the content area before clicking the button.
You can also insert HTML at the current position of a contentEditable element by using
`insertHTML`command. Check out this example:
// Get the current selectionconst selection = window.getSelection();// Get the HTML to insertconst htmlToInsert = '<div>Hello, world!</div>';// Insert the HTML at the current positiondocument.execCommand('insertHTML', false, htmlToInsert);
In this example, we first get the current selection and save it. Then, we define the HTML we want to insert as a string variable. Finally, we use the
`execCommand`method with the
`insertHTML`command to insert the HTML at the current position.
It's important to note that while this method is simpler than creating a new element and inserting it with
`range.insertNode()`, it may not work in all browsers.
`execCommand`method is also useful for formatting selected text. For example, you can make the selected text bold by using the
// Get the current selectionconst selection = window.getSelection();// Use execCommand to make selected text bolddocument.execCommand('bold', false, null);
To create a link around selected text, you can use the
`'createLink'`command and pass in a URL argument. For example:
// Get the current selectionconst selection = window.getSelection();// Use execCommand to create a link around selected textdocument.execCommand('createLink', false, 'https://phuoc.ng');
This will create a link around any selected text with the provided URL.
Do you have any questions about front-end development? If so, feel free to reach out to me on Twitter or create a new issue on GitHub using the button below. I'm happy to help with any topic you'd like to learn more about, even beyond what's covered in this post.
While I have a long list of upcoming topics, I'm always eager to prioritize your questions and ideas for future content. Let's learn and grow together! Sharing knowledge is the best way to elevate ourselves 🥷.
Recent posts ⚡
Use forwardRef with a higher-order component
05 Dec, 2023
Swap items in a sortable list
04 Dec, 2023
Display a placeholder in a sortable list
03 Dec, 2023
Create a sortable list
02 Dec, 2023
Build a drop zone for file uploads
01 Dec, 2023
Read the content of the dropped file
30 Nov, 2023
Preview images before uploading them
29 Nov, 2023
Build a drop file indicator
28 Nov, 2023
Create your own ghost element
27 Nov, 2023
Customize the appearance of a ghost element
26 Nov, 2023
An introduction to HTML 5 drag and drop
25 Nov, 2023
Use a custom drag handle
24 Nov, 2023
Create a linear gauge with discrete values
22 Nov, 2023
If you're into front-end technologies and you want to see more of the content I'm creating, then you might want to consider subscribing to my newsletter.
By subscribing, you'll be the first to know about new articles, products, and exclusive promotions.
Don't worry, I won't spam you. And if you ever change your mind, you can unsubscribe at any time.