Elements with the contenteditable
attribute added to it lets users edit the content inside the element.
Sometimes, we may want to listen for change events that are made to the element.
In this article, we’ll look at how to listen for changes triggered in elements that have the contenteditable
attribute applied.
Listen to the input Event Emitted by the Element
When we change the content of an element that has the contenteditable
attribute added, then input
event will be emitted.
Therefore, we can listen to the input
event of the element to listen for changes in its content.
For instance, we can write the following HTML:
<div contenteditable>
hello world
</div>
And then we can add an event listener with the addEventListener
with:
const div = document.querySelector("div")
div.addEventListener("input", (e) => {
console.log(e);
}, false);
When we change the content in the div, we’ll see the input
event listener run.
We can get the element’s attributes and styles with the e.target
property.
The e.timestamp
property is the time in milliseconds at which the event is created.
MutationObserver
We can also use the MutationObserver
to watch for changes to the content of an element.
This is because it can listen for changes in the DOM, including any content changes in an element.
For instance, we can write:
const div = document.querySelector("div")
const observer = new MutationObserver((mutationRecords) => {
console.log(mutationRecords[0].target.data)
})
observer.observe(div, {
characterData: true,
subtree: true,
})
and keep the HTML the same.
We pass in a callback with the mutationRecords
object to get the mutation records.
chartacterData
set to true
means we watch for text content changes.
And subtree
set to true
means we watch for the element’s DOM subtree changes.
We get the latest content of the div with the mutationRecords[0].target.data
property.
Conclusion
We can watch for changes of the content of an HTML with the contenteditable
attribute applied with the MutationObserver
or listen to the input
event of the element.