AddEventListener is not a function appears in js
textarea.addEventListener is not a function
Business scenario:
https://juejin.cn/post/6978721383983530015
Error screenshot:
Cause Analysis:
js addEventListener is not a function
, most likely the event source of the listening event is incorrect, and the event source should be an element, not an array.
getElementsByClassName
, getElementByTagName()
all obtained are arrays, even if there is only one element that satisfies the condition, it is still an array.
Therefore, when listening to events, [0] must be added, otherwise the following error will be reported
Solution:
// autoHeightTextarea();//textarea 自动撑高
var textarea = document.getElementsByClassName('autoh');
textarea[0].addEventListener('input', (e) => {
textarea[0].style.height = '180px';
textarea[0].style.height = e.target.scrollHeight + 'px!important';
// console.log(e);
});
Reference article:
https://blog.csdn.net/weixin_47417033/article/details/124261891