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 ?
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.
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 () {} .
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.
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!
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With