1

Example:

<div id="184" style="position: relative;" class="EditBox" tabindex="0" contenteditable="true">SomeText</div>

What I want to achieve is when the user copy the text, prevent copying its style. Is there a way using DOM or javascript or anything possible to do that?

  • Does this answer your question? [There is some way to ignore the css style on copy?](https://stackoverflow.com/questions/11802083/there-is-some-way-to-ignore-the-css-style-on-copy) – Jonathan Hall Dec 04 '19 at 09:34

2 Answers2

2

I solved it by adding an event listener to the div or input, which intercepts the copy command and instead it copies the plain text instead of the html style:

document.querySelector("div[contenteditable]").addEventListener('copy', function(e) {
alert('Copied');
   e.clipboardData.setData('text/plain', 'Hello! Welcome');
   e.preventDefault();
 });
1

use innerText and textContent to get copy the text

let text = document.getElementById("184").innerText || document.getElementById("184").textContent;

function myFunction() {
  const el = document.createElement('textarea');
  el.value =  document.getElementById("184").innerText;
  document.body.appendChild(el);
  el.select();
  document.execCommand('copy');
  document.body.removeChild(el);
}
.EditBox{
 color: blue;
}
<div id="184" style="position: relative;" class="EditBox" tabindex="0" contenteditable="true">SomeText</div>

<button onclick="myFunction()">Copy text</button>
Mohammad Ali Rony
  • 4,695
  • 3
  • 19
  • 33
  • Thanks @Mohammad but what I needed not just get the text but a full interaction with the clipboard, that was the issue, I needed to prevent the html style from being applied to the text of clipboard, so simply plain text instead. – Mohamed Aloui Dec 04 '19 at 10:05