Skip to content

Instantly share code, notes, and snippets.

@ivanhoe011
Created March 2, 2023 11:59
Show Gist options
  • Save ivanhoe011/95dd4ca8dbfa5daac85e6fcf1aa829e6 to your computer and use it in GitHub Desktop.
Save ivanhoe011/95dd4ca8dbfa5daac85e6fcf1aa829e6 to your computer and use it in GitHub Desktop.
Get html from clipboard with js
document
// can be any element that knows how to recieve the paste event
.getElementById('someElement')
// add event listener
.addEventListener('paste', e => {
if (! e.clipboardData.types.includes('text/html')) {
// if there's no html on the clipboard ignore it
return;
}
// use <template> to convert the html string to a DOM tree
const tpl = document.createElement('template');
// get clipboard content (always trim to avoid creating empty text nodes)
tpl.innerHTML = e.clipboardData.getData('text/html').trim();
// get html as DOM elements
const html = tpl.content.children;
// do something with it...
// if you don't want to paste the text version of the clipboard, prevent the default action
e.preventDefault();
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment