js how to add a short function addEventListener



  • function get(s){
        return document.querySelector(s);
    }
    
    function getAll(s){
        return document.querySelectorAll(s);
    }
    Node.prototype.click=function(ev){
        this.addEventListener("click",ev)
    }
    
    NodeList.prototype.click=function(ev){
        this.forEach(el=>el.addEventListener("click",ev))
    }
    
    window.onload=function(){
        get("b").click(function(){
            console.log(this)
        })
    
        getAll("b").click(function(){
            console.log(this)
        })
    }
    
    <b>1</b>
    <b>2</b>
    <b>3</b>
    <b>4</b>
    <b>5</b>
    

    NodeList works and node why not. What's the problem?



  • Problem in the number of implementation levels:

    https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelector returning the particular https://developer.mozilla.org/en-US/docs/Web/API/Element

    The number of prototypes of the component obtained is as follows:

    HtmlElement
    Element
    Node
    

    At the same time, ownership click I've got one. HtmlElement

    Thus, search before Node.prototype.click It just doesn't work.



Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2