addEventListener is not a function, JavaScript reports an error when adding a listening event

a07b89a158ba4990937a36f426558ebc.png

Brief description: When writing js code, the console sometimes encounters such an error, addEventListener is not a function, saying that addEventListener is not a function. The specific reason is because the event source for monitoring the event is wrong. The event source should be an element. , rather than others;

 

Therefore, we must pay attention when obtaining elements,

getElementsByClassName()、

getElementByTagName(),

What is obtained is an array. Even if there is only one element that meets the condition, it is returned in the form of an array.

eg:

1794c3202f4b450aadf07be45fd1b434.png

 Console output:

959658b34c6d42a59f8e6ce9658528b4.png

The monitored event source is an array, not an element, so when adding addEventListener() to btn to listen for events, an error will be reported. GetElementByTagName() is similar.

You can write it like this, array [0], or use the querySelector method to solve it;


btn[0].addEventListener('click', function () {
  console.log("enumerable");
})

const btnTwo = document.querySelector(".submitIpt")
btnTwo.addEventListener("click", (() => {
  console.log("immediate");
}))

 

 

Guess you like

Origin blog.csdn.net/weixin_65793170/article/details/129689602