简体   繁体   中英

How to get html element without its children in JavaScript?

I would like to get an html element without its children, to set an event addEventListener("click) on it, so that the function will only be executed when it is clicked, not on its children. I can only use Javascript. Is this possible?

 const divs = document.querySelectorAll("div"); const body = document.querySelector("body"); const myFunction = function() { this.classList.add("clicked") } divs.forEach(function(element) { element.addEventListener("click", myFunction) });
 .grandparent { padding: 20px; border: 5px solid black; } .parent { padding: 20px; border: 5px solid blue; } .child { padding: 20px; height: 100px; width: 100px; border: 5px solid yellow; } .clicked { background-color: red; }
 <div data-time="3000" class="grandparent"> <div data-time="2000" class="parent"> <div data-time="1000" class="child"></div> </div> </div>

this function adds a class to each div, now I would like clicking outside of div to remove that class, however the body variable contains including its children.

If you want to ignore all and any child clicks, then check if the currentTarget is different than the target of the event.

  • target is the element the event originated from ( the deepest child that received the event )
  • currentTarget is the element on which the event handler is attached

 const divs = document.querySelectorAll("div"); const body = document.querySelector("body"); const myFunction = function(event) { if (event.target === event.currentTarget) { this.classList.add("clicked") } } divs.forEach(function(element) { element.addEventListener("click", myFunction) });
 .grandparent { padding: 20px; border: 5px solid black; } .parent { padding: 20px; border: 5px solid blue; } .child { padding: 20px; height: 100px; width: 100px; border: 5px solid yellow; } .clicked { background-color: red; }
 <div data-time="3000" class="grandparent"> <div data-time="2000" class="parent"> <div data-time="1000" class="child"></div> </div> </div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM