How to capture text from nested divs in an elegant way?

1

This post explains how to copy plain text to the clipboard using the ZeroClipboard .

But a reader came up with a question: how do you get the content of a <div> with multiple child divs within it? When we use the above example strictly speaking, a lot of space is transmitted (the tabs of the source code).

How can I solve this problem?

    
asked by anonymous 29.06.2016 / 22:26

1 answer

2

I can not test ZeroClipboard because I do not have Flash on my computer, but I'm going to risk an answer since the doubt is more about capturing text and manipulation than the library itself.

Because this library provides an API that enables you to later copy the content with the setData() , first get the contents of the element (removing the spacing) and then call this function with the "clean result" of the element.

(function(){
  
  // Retorna o conteúdo textual do elemento.
  function text(el){
    return el.innerText || el.textContent || '';
  }
  
  // Remove as quebras de linhas da string.
  function clean(str){
    return str.replace(/\r?\n/gm, ' ');
  }

  
  var elemento = document.getElementById('foo');
  
  var conteudo = text(elemento);
  alert('ANTES:\n\n' + conteudo);
  
  conteudo = clean(conteudo);
  alert('DEPOIS:\n\n' + conteudo);
  
  // copia 'conteudo' para o clipboard.

})();
<div id='foo'>
  Mussum Ipsum, cacilds vidis litro abertis.
  <div>
    Casamentiss faiz malandris se pirulitá.
    <div>
      Si num tem leite então bota uma pinga aí cumpadi!
      <p>
        Quem num gosti di mum que vai caçá sua turmis!
      </p>
    </div>
  </div>
</div>
    
29.06.2016 / 22:59