Get parentNode of clicked element in plain JS

I need to get the parentNode of an element with a click in simple JS (without jQuery or other frameworks) I am currently using document.getElementById("item_click") but I want to change id="item_click" to class="item_click" to use multiple boxes . I just don't know how to integrate this into a script

Here is the script <<<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 since this will be window (I think)

BTW. I need an event, since this is just a parsing of all the code that I use.

+4
source share
2 answers
 function new_class(event) { wTile = event.target.parentNode; wTile.className = wTile.className + " added-class"; } 
+6
source

"I just don't know how to integrate this into a script"

Use .call() to call a handler to set its this value to an element that has a 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"; } 
+2
source

Source: https://habr.com/ru/post/1396049/


All Articles