Performing an action on Parent/Child elements independently.

Posted by Matt Weldon on Stack Overflow See other posts from Stack Overflow or by Matt Weldon
Published on 2010-06-02T12:23:18Z Indexed on 2010/06/02 12:33 UTC
Read the original article Hit count: 193

Filed under:
|
|

I have HTML similar to the following in my page

<div id="someDiv">
    <img src="foo.gif" class="someImg" />
</div>

The wrapper div is set up such that when it is clicked, it's background-color changes using the following jQuery code.

$("div").click(function(event){
    $(this).css("background-color", "blue");
});

I also have some jQuery associated with my img that will do some other function (for the sake of argument I am going to display and alert box) like so:

$("img[class=someImg]").click(function(event){
    alert("Image clicked");
});

The issue I have come across is that when I click on the img, the event associated with the div is also triggered. I'm pretty sure that this is due to the way that jQuery (or indeed JavaScript) is handling the two DOM elements - clicking the img would require you to also technically click the div, thus triggering both events.

Two questions then really:

  1. Is my understanding of the DOM/JavaScript flawed in some way or is this actually how things are occurring?
  2. Are there any jQuery methods that would allow me to perform actions on a child element without invoking those associated with its parent?

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about jQuery