Subscribe

Did you know HTML elements can be editable?

✍️

Having some fun with the contenteditable HTML tag

25 Aug, 2020 · 2 min read

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!)

See the Pen Did you know HTML elements can be editable? by Chris Bongers (@rebelchris) on CodePen.

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>

It can have three values:

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

Capturing changes in JavaScript

This is cool but it doesn’t do much on its own, so we can use JavaScript to capture the changes.

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

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

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

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

Spread the knowledge with fellow developers on Twitter
Tweet this tip
Powered by Webmentions - Learn more

Read next 📖

Submit button outside the form

4 Dec, 2022 · 1 min read

Submit button outside the form

Trying out native dialog modals

8 Aug, 2022 · 3 min read

Trying out native dialog modals

Join 2099 devs and subscribe to my newsletter