DEV Community

Cover image for Did you know HTML elements can be editable?
Chris Bongers
Chris Bongers

Posted on • Originally published at daily-dev-tips.com

Did you know HTML elements can be editable?

This is one of the HTML options you don't see often, but are actually really cool.

There is an HTML attribute called contenteditable, and it allows HTML elements to become editable 🙊.

Let me show you how it looks on this Codepen.
(Click any text!)

HTML contenteditable

We can simply make an element editable by adding the contenteditable tag.

<div class="container">
  <h1 contenteditable="true">Welcome click me 🎯</h1>
  <p contenteditable="true">
    Did you know you can click me to edit my content?<br />
    Even big paragraphs 👀
  </p>
  <a contenteditable="true" href="#">View the full article</a>
</div>
Enter fullscreen mode Exit fullscreen mode

It can have three values:

  • contenteditable="true" ~ We can change the content
  • contenteditable="false" ~ Not able to change it
  • contenteditable="inherit" ~ What ever the parent has

Capturing changes in JavaScript

Of course, this is cool, but it doesn't do much on its own, we can actually capture these changes with JavaScript.

Let's bind an event listener to the input event for each contenteditable tag.

var contents = document.querySelectorAll('[contenteditable]');

for (let content of contents) {
  content.addEventListener('input', function() {
    console.log('input changed to: ' + content.innerHTML);
  });
}
Enter fullscreen mode Exit fullscreen mode

Browser Support

Since this is a native HTML tag, it has amazing support!

Contenteditable support

Thank you for reading, and let's connect!

Thank you for reading my blog. Feel free to subscribe to my email newsletter and connect on Facebook or Twitter

Top comments (2)

Collapse
 
bias profile image
Tobias Nickel

really? I have to try this ! ! this is very cool, thanks !

Collapse
 
dailydevtips1 profile image
Chris Bongers

Yep! Hidden gems, but be aware, it's nothing like a WYSWYG Editor or secure.
Let me know what you are building

A cool idea is a visual email checker for marketeers (checking title lengths etc)