When defining events in javascript, "Type Error: element.addEventLester is not a function", and event definition is not possible.

Asked 1 years ago, Updated 1 years ago, 25 views

Currently, I am trying to register an event listener with the original JavaScript, but it seems that "addEventLester" itself is not recognized as a function.

The original object was an HTML element, where varisbn= document.getElementsByName("isbn"); was written.

When I checked Object.values(isbn); to see if the element has been retrieved, it seems that the element has been retrieved successfully.

The code is as follows:

window.addEventListener('DOMContentLoaded', function(){

    varisbn = document.getElementsByName('isbn');
    console.log (Object.values(isbn));
    getBookData(isbn);

}, false);

function getBookData(element){

    element.addEventListener('change', function(){
        // processing
    }, false);

}

And the HTML elements you are getting are as follows:

<input type="number" class="form-control" name="isbn" maxlength="13" value="placeholder=""required>

javascript

2022-09-30 16:38

1 Answers

The return value for the getElementsByName method is NodeList object.

3 3.1.3 DOM tree accessors[1]

[1]

The getElementsByName(name) method takes a string name, and must return a live NodeList containing all the HTML elements in that document that have a name attribute which is equal to the name argument (in a case-sensitive manager), in tree order.

The Node interface inherits the EventTarget interface [2], but the NodeList interface does not inherit the EventTarget interfacehttps://dom.spec.whatwg.org/[2][3]

Therefore, in order for the question text to work, you must perform a process to apply the addEventListener method to each NodeList object.

window.addEventListener(
  "DOMContentLoaded",
  function(){
    varisbn= document.getElementsByName("isbn");
    getBookData(isbn);
  },
  false
);

function getBookData(element){
  element.forEach(e=>{
    e.addEventListener(
      "change",
      function(){
        console.log(e.value);
      },
      false
    );
  });
}
<input type="number" class="form-control" name="isbn" maxlength="13" value="placeholder=""required>

Note:


2022-09-30 16:38

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.