Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Uncaught TypeError: text.select is not a function

Tags:

javascript

I am trying to implement copy to clipboard feature using javascript which is meant to copy the text in the text area when the copy button is clicked by the user. This is the code from script which is meant to do this feature.

var item = document.getElementsByClassName('js-copyBtn');

for(var i=0; i < item.length; i++){
    item[i].addEventListener('click', function(event){

        var text = document.getElementsByClassName('js-text');
        text.select();

        try{
            var successful = document.execCommand('copy');
            var msg = successful ? 'successful' : 'unsuccessful';    
            console.log('Copy was ' + msg);  
       } catch(err) {  
         console.log('Oops, unable to copy');  
       }  
    });
}

However when i run this, i am getting an error on google chrome console saying Uncaught TypeError: text.select is not a function. I have also tested this on other browsers but getting the same result. Anyone else came across this problem ?

like image 819
r1993 Avatar asked Aug 23 '16 08:08

r1993


People also ask

Is not a function TypeError?

A TypeError: "x" is not a function occurs when a function is called on an object that does not contain the called function. When calling a built-in function that expects a callback function argument, which does not exist. When the called function is within a scope that is not accessible.

Is not a function JavaScript onclick?

onclick is not a function" error occurs, because there is no onclick() function in jQuery. To solve the error, use the click function instead, e.g. $('#btn'). click(function () {} .

Is not function?

The NOT Function[1] is an Excel Logical function. The function helps check if one value is not equal to another. If we give TRUE, it will return FALSE and when given FALSE, it will return TRUE. So, basically, it will always return a reverse logical value.


2 Answers

I ran into this problem today and felt frustrated just as you when the marked answer didn't work for me. After some additional thinking i realised my problem was trying to paste into paragraph element <p></p>. When I changed it to textarea it worked well. So you indeed had a problem with the access to the array but when you finally got to the specific element you should have made sure its an editable element.

Good luck!

like image 90
olevran Avatar answered Sep 17 '22 11:09

olevran


getElementsByClassName returns a HTMLCollection of found elements not an individual element. A HTMLCollection indeed does not have a select function.

You probably want the first element in the collection

var text = document.getElementsByClassName('js-text');
text[0].select();
like image 33
Jamiec Avatar answered Sep 16 '22 11:09

Jamiec