Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

246
Views
How to event click on DIV except if the clicked element is a specific one

I have a div with several elements. I want to make an event to handle clicking on any element of this div, EXCEPT a specific one.

<div id="mydiv">
<img id="myimage" src="myimage.gif"/>
<img id="myimage2" src="myimage2.gif"/>
<img id="myimage3" src="myimage3.gif"/>
</div>

<script>
document.getElementById('mydiv').addEventListener('click', function() {
// if element is not the one with id=myimage3 do something
alert('You clicked on image1 or image2');
});
</script>
about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

Use the event parameter to the callback and check that its targets id attribute is not myimage3:

document.getElementById('mydiv').addEventListener('click', function(e) {
  if (e.target.id != 'myimage3')
    alert('You clicked on image1 or image2');
});
<div id="mydiv">
  <img id="myimage" src="https://via.placeholder.com/100?text=image1" />
  <img id="myimage2" src="https://via.placeholder.com/100?text=image2" />
  <img id="myimage3" src="https://via.placeholder.com/100?text=image3" />
</div>

about 4 years ago · Juan Pablo Isaza Report

0

Elements in HTML can be identified is a few different ways: by class and by id. Classes are collections of elements that can be selected, styled, and further manipulated whereas ids are unique are should be specific to a single element. Since you want to exclude a specific element from being selected, you'll need to compare the selected element's id with that of the one you wish to exclude.

This can be done with a callback like in @Nick 's answer using the event.target property.

Essentially what e.target does is it gets the element which triggered the event and all of its various attributes eg. tagName and style.

  • https://developer.mozilla.org/en-US/docs/Web/API/Event/target#example
about 4 years ago · Juan Pablo Isaza Report

0

Pass 'event' as an argument to the callback function.

Wrap the alert in an if statement checking if the

event.target.id !== 'myimage3'
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!