0

How to use jquery selectors to select parent only but exclude child

HTML

<div id="container">
  <div class="element">
    <img src="something.jpg"/>
    <a href="somelink">Some link</a>
    <p>Blah blah...</p>
  </div>
  <div class="element">
    <img src="something2.jpg"/>
    <a href="somelink2">Some link2</a>
    <p>Blah blah...</p>
  </div>
</div>

JQuery:

How can I trigger alert("Hi") only if user clicks on (div "element") but not when < a > and < img > are clicked

                    $("#container").delegate(".element", "click", function(){
                        alert("Hi");
                    });
user6890
  • 484
  • 2
  • 6
  • 16

2 Answers2

1

Events bubble up the DOM unless you explicitly stop their propagation. I recommend that you try to work with this, not against it. That said, if you insist, examine event.target to make sure that the div.element was clicked, and not one of its children:

$("#container").delegate(".element", "click", function(event) {
    if (!$(event.target).hasClass("element")) return;
    alert("Hi");
});

http://jsfiddle.net/mattball/JMDLq/

Matt Ball
  • 354,903
  • 100
  • 647
  • 710
0

I've just answered the same question yesterday, search a bit before asking.

https://stackoverflow.com/a/10440234/1331430

Just replace the 2 ID selectors there by $('.element') and you're all set.

Community
  • 1
  • 1
Fabrício Matté
  • 69,329
  • 26
  • 129
  • 166
  • Hi thanks for your input.. believe me.. ive searched alot... i know it is important to keep the knowledge base streamlined... however my searches couldn't yield a solution that worked. ive googled a bunch like: jquery select parent exclude child... came up with no workable solution – user6890 May 05 '12 at 07:40