How to filter insert html from some tags (contenteditable)

362 Views Asked by At

I have a tag div with an contenteditable = true attribute.When Paste events happen I want to filter pasted html from some tags.How can i do this ?

2

There are 2 best solutions below

0
Spectric On

Listen for the paste event and assign the textContent to the innerHTML. Thanks to the nature of textContent, HTML tags are removed but the output in text is preserved.

We use setTimeout in the event listener to account for the fact that the paste event handler is fired before the content is updated.

document.querySelector('div').addEventListener('paste', function() {
  setTimeout(() => {
    this.innerHTML = this.textContent;
  }, 0);
})
<div contenteditable="true">

</div>

0
Titus On

You can just query the div for specific elements. Here is an example:

const div = document.querySelector('div')
div.addEventListener('paste', e => {
  setTimeout(() => {
    const elements = getTags('strong');
    console.log('@the paste event, tags count: ', elements.length);
  }, 0);
});

function getTags(tagName) {
  return [...div.querySelectorAll(tagName)];
}

console.log('tags count: ', getTags('strong').length);
<div contenteditable="true" style="border 1px solid black; width: 200px; height: 200px">
  <strong>Some </strong><span>thing </span><strong>for </strong><span>testing</span>
</div>

The getTags function just query the contenteditable <div> for elements that have a specific tag name. I've filled this <div> with some content by default to show this working without using the paste event.

Also, in the paste event listener I've used setTimeout to make sure the DOM is updated with the new elements before trying to get the element's we are interested in.