get parentNode of clicked element in plain JS

前端 未结 3 1532
误落风尘
误落风尘 2020-12-10 14:50

I need to get the parentNode of a clicked element in plain JS (no jQuery or other frameworks) I am currently using document.getElementById(\"item_click\") but

相关标签:
3条回答
  • 2020-12-10 14:56
    function new_class(event) {
        wTile = event.target.parentNode;
        wTile.className = wTile.className + " added-class";
    }
    
    0 讨论(0)
  • 2020-12-10 15:01

    "I just don't know how to integrate this in the script"

    Use .call() to invoke the handler to set its this value to the element that has the handler...

    <div id="item_click" onmousedown="new_class.call(this,event)" ...>
    

    function new_class(event) {
        var wTile = this.parentNode;
        wTile.className = wTile.className + " added-class";
    }
    
    0 讨论(0)
  • 2020-12-10 15:07

    You can just use event.target.parentNode (Don't need to even pass the event in the function):

    function new_class() {
        var parent = event.target.parentNode;
        // Do whatever...
    }
    
    0 讨论(0)
提交回复
热议问题