Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

192
Visualizações
Copy innertext from a contenteditable div?

I know that there is a similar question but when I try it, it doesn't work. I figured out that it's because I've changed the position of the button above the div I want to copy, but I don't know how to fix it :/ I must say I haven't understood the JS :/

  function copy() {
      var target = document.getElementById('mydiv');
      var range, select;
      if (document.createRange) {
        range = document.createRange();
        range.selectNode(target)
        select = window.getSelection();
        select.removeAllRanges();
        select.addRange(range);
        document.execCommand('copy');
        select.removeAllRanges();
      } else {
        range = document.body.createTextRange();
        range.moveToElementText(target);
        range.select();
        document.execCommand('copy');
      }
    }
#mydiv{
border: solid black 1px;
border-radius: 4x;
margin: 10px 0px;
}
<input onclick="copy()" type="button" value="Copy" />
<p></p>
<div>Insert text below</div>
<div id="mydiv" contenteditable="true"></div>

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Use range.selectNodeContents(target) instead of range.selectNode(target) to avoid copying the outerHTML as well

  function copy() {
      var target = document.getElementById('mydiv');
      var range, select;
      if (document.createRange) {
        range = document.createRange();
        range.selectNodeContents(target)
        select = window.getSelection();
        select.removeAllRanges();
        select.addRange(range);
        document.execCommand('copy');
        select.removeAllRanges();
      } else {
        range = document.body.createTextRange();
        range.moveToElementText(target);
        range.select();
        document.execCommand('copy');
      }
    }
#mydiv{
border: solid black 1px;
border-radius: 4x;
margin: 10px 0px;
}
<input onclick="copy()" type="button" value="Copy" />
<p></p>
<div>Insert text below</div>
<div id="mydiv" contenteditable="true"></div>

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda