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>
CodePudding user response:
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>
CodePudding user response:
Elements in HTML can be identified is a few different ways: by class
and by id
. Class
es are collections of elements that can be selected, styled, and further manipulated whereas id
s 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
.
CodePudding user response:
Pass 'event' as an argument to the callback function.
Wrap the alert in an if statement checking if the
event.target.id !== 'myimage3'