get parentNode of clicked element in plain JS

两盒软妹~` 提交于 2019-12-06 01:34:04

问题


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 I want to change id="item_click" to class="item_click" so I can use multiple boxes. I just don't know how to integrate this in the script

Here's a Fiddle <<< play with it

HTML

<div class="item">
    <div  class="item-tester" >
        <div class="item-icon"></div>
        <div class="item-title">Item Title</div>
    </div>
    <div id="item_click" onmousedown="new_class(event)" onmouseup="revert_class(event)" onmouseout="revert_class(event)"></div>
</div>

JS

function new_class(event) {
    wClick = document.getElementById("item_click");
    wTile = wClick.parentNode;
    wTile.className = wTile.className + " added-class";
}
function revert_class(event) {
    wTile.className = "item";
}
​

I want to change

wClick = document.getElementById("item_click");
wTile = wClick.parentNode;

to something like

wClick = this;
wTile = wClick.parentNode;

I know how to do this in jQuery but it will not work in plain JS as this would be the window (I think)

BTW. I need the (event) since this is just a stripdown of the entire code I'm using.


回答1:


function new_class(event) {
    wTile = event.target.parentNode;
    wTile.className = wTile.className + " added-class";
}



回答2:


"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";
}



回答3:


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...
}


来源:https://stackoverflow.com/questions/9250634/get-parentnode-of-clicked-element-in-plain-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!