clubmate.fi

A good[ish] website

Web development blog, loads of UI and JavaScript topics

Make any HTML element editable with contenteditable attribute

Filed under: HTML/CSS— Tagged with: css, UI components

Any element’s content can be made editable same way form fields are, even divs, by using the contenteditable attribute.

<div id="editable-div" contenteditable>Hello!</div>

You can just edit that div 👇

Hello!
Value: Hello!

Listening changes on contenteditable element

Normal onChange event, which you would listen on a normal form field, won’t work in a contenteditable field, and event.target.value is not a thing. But you can listen to the input event, and the elements value can be accessed with event.target.innerText:

const editableDiv = document.getElementById('#editable-div')

editableDiv.addEventListener('input', event => {
  console.log(event.target.innerText)
})

Also, you’ve got access to Document.execCommand() when the div is made editable.

contenteditable React component

React is winching about that:

Error message from JavaScript console
Warning: A component is `contentEditable` and contains `children` managed by React. It is now your responsibility to guarantee that none of those nodes are unexpectedly modified or duplicated. This is probably not intentional.

Event though I don’t have any children in there...

As a React component, the above editable element demo would look like this:

const EditableDiv = () => {
  const [divText, setDivText] = React.useState('Hello!')

  return (
    <>
      <div
        className="pink-div"
        contenteditable
        onInput={event => setDivText(event.target.innerText)}
      >
        Hello!
      </div>
      <div className="value-container">
        <strong>Value:</strong> {divText}
      </div>
    </>
  )
}

Conclusions

I’m slightly unsure where to use this... You could build a simple text editor with it, and it’s great for demos and such.

Comments would go here, but the commenting system isn’t ready yet, sorry. Tweet me @hiljaa if you want to make a correction etc.

  • © 2021 Antti Hiljá
  • About
  • Follow me in Twatter → @hiljaa
  • All rights reserved yadda yadda.
  • I can put just about anything here, no one reads the footer anyways.
  • I love u!