There is a table in which you need to select and copy two lines when you click on the button.

http://codepen.io/tews/pen/EPyyBJ

var copyNameBtn = document.querySelector('.copyname-btn'); copyNameBtn.addEventListener('click', function(event) { // Π’Ρ‹Π±ΠΎΡ€ΠΊΠ° строки ΠΈΠΌΠ΅Π½Π΅ΠΌ var nameStr = document.querySelector(".name"); var range = document.createRange(); range.selectNode(nameStr); window.getSelection().addRange(range); try { // Π’Π΅ΠΏΠ΅Ρ€ΡŒ, ΠΊΠΎΠ³Π΄Π° ΠΌΡ‹ Π²Ρ‹Π±Ρ€Π°Π»ΠΈ тСкст , Π²Ρ‹ΠΏΠΎΠ»Π½ΠΈΠΌ ΠΊΠΎΠΌΠ°Π½Π΄Ρƒ копирования var successful = document.execCommand('copy'); var msg = successful ? 'successful' : 'unsuccessful'; console.log('Copy email command was ' + msg); } catch(err) { console.log('Oops, unable to copy'); } // БнятиС выдСлСния // removeRange(range) ΠΊΠΎΠ³Π΄Π° это Π²ΠΎΠ·ΠΌΠΎΠΆΠ½ΠΎ window.getSelection().removeAllRanges(); }); 

Only the Name is copied, and it is necessary that when you click the name + surname is copied.

Those. Now when you press the button, only "Petya" is copied, but it is necessary that "Petya + Pupkin" be copied.

  • one
    I haven't copied anything at all - Serge Esmanovich 2015
  • and so ".name"+".patronymic" is it possible to do? ....... Your code is not working, by the way - Alexey Shimansky
  • Look at the code on 2ip.ru, which is processed by clicking on the IP address. - Steve
  • @ Alexey Shimansky, why not? two strings are simply concatenated - Grundy
  • Uncaught TypeError: Failed to execute 'selectNode' on 'Range': parameter 1 is not of type 'Node'. - Grundy

1 answer 1

querySelector takes the first matching element to find several; you can use querySelectorAll:

 name = querySelectorAll(".name, .patronymic"); 

then the selected elements can be obtained as follows:

 firstname = name[0]; surname = name[1]; 

if they are unique, otherwise it is a rather clumsy method, a simple example: https://jsfiddle.net/nhsutj0n/