Skip to content

Instantly share code, notes, and snippets.

@josecaos
Last active March 7, 2019 19:55
Show Gist options
  • Select an option

  • Save josecaos/4a87ca9e85930d3e742228c611c8bafe to your computer and use it in GitHub Desktop.

Select an option

Save josecaos/4a87ca9e85930d3e742228c611c8bafe to your computer and use it in GitHub Desktop.
Copy all content from div
<div id="htmlcode" onclick="selectContent()">XXXXXXXXXXXXX</div>
<style>
function selectContent() {
const node = document.getElementById('htmlcode')
if (document.body.createTextRange) {
const range = document.body.createTextRange()
range.moveToElementText(node)
range.select()
document.execCommand('copy')
alert("copied to clipboard: " + range)
} else if (window.getSelection) {
const selection = window.getSelection()
const range = document.createRange()
range.selectNodeContents(node)
selection.removeAllRanges()
selection.addRange(range)
document.execCommand('copy')
alert("copied to clipboard: " + range)
} else {
console.warn("Could not select content: Unsupported browser.")
}
}
//in case of using a parameter to pass the eventListener
//const clickable = document.querySelector('htmlcode')
//clickable.addEventListener('click', () => selectContent('htmlcode'))
</style>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment