How to make a span element editable with JavaScript?

Sometimes, we want to make a span element editable with JavaScript.

In this article, we’ll look at how to make a span element editable with JavaScript.

How to make a span element editable with JavaScript?

To make a span element editable with JavaScript, we can set the contentEditable property of the span to true.

For instance, we write:

<span>hello world</span>
<button>
  edit
</button>

to add a span and a button.

Then we write:

const button = document.querySelector('button')
const span = document.querySelector('span')

button.onclick = () => {
  span.contentEditable = true
}

to make the span editable when we click on the button.

To do this, we select the span and button with querySelector.

Then we set button.onclick to a function that sets span.contentEditable to true.

As a result, when we click edit, then we can change the span’s text by typing in it.

Conclusion

To make a span element editable with JavaScript, we can set the contentEditable property of the span to true.