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 ?
How to filter insert html from some tags (contenteditable)
362 Views Asked by AudioBubble At
2
There are 2 best solutions below
0
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.
Listen for the
pasteevent and assign thetextContentto theinnerHTML. Thanks to the nature oftextContent, HTML tags are removed but the output in text is preserved.We use
setTimeoutin the event listener to account for the fact that thepasteevent handler is fired before the content is updated.