How to capture the text of nested Ivs in an elegant way?

Asked

Viewed 159 times

1

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

But a reader brought a doubt: how to take the content of a <div> with several daughters within it? When we use the above example strictly speaking, a lot of space is transmitted (the tabs of the source code).

How to solve this problem?

1 answer

2


I can’t test Zeroclipboard because I don’t have Flash on my computer, but I will risk an answer since the doubt is more related to text capture and manipulation than the library itself.

How this library provides an API that allows you to copy content later with the function setData(), first get the element content (removing 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>

  • OFF: Use the clipboardjs instead of Zero, in case you don’t have to support old browsers.

  • Thanks for the quick response. I didn’t know about these libraries, I’ll take a look at it later.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.