0
<section id="first">
    <h1>Colors</h1>
    <section id="red">
        <h1>Red</h1>
        <section id="apples">
            <h1>Apples</h1>
        </section>
        <section id="apples">
            <h1>Strawberries</h1>
        </section>
    </section>
    <section id="orange">
        <h1>Orange</h1>
    </section>
</section>

$('section').click(function(){
    $(this).css('color','yellow');
});

http://jsfiddle.net/J9kAV/

I want the sections to turn yellow when they are clicked. However, as $('section') could also refer to their parent elements, it's applying the CSS to them as well.

How can I tell jQuery to apply the CSS to the clicked child element only and not the parent?

I don't want to use $('section section') because I would also like the parent elements to turn yellow if they are clicked specifically. So I need a JavaScript/jQuery solution, not a selector or HTML solution.

3 Answers3

4

Use this:

e.stopPropagation();

Example: http://jsfiddle.net/8KLEK/

myfunkyside
  • 3,890
  • 1
  • 17
  • 32
  • 2
    `e.stopPropagation()` also works. – King King Jun 09 '14 at 21:58
  • 1
    @user3650808 - KingKing is right, better use `e.stopPropagation`, otherwise any other handlers on the clicked element itself might also be prevented ([see this link](http://stackoverflow.com/questions/5299740/jquery-stoppropagation-vs-stopimmediatepropagation)) – myfunkyside Jun 09 '14 at 22:03
0

Try this:

$('section').click(function(e){
    e.stopImmediatePropagation();
    $(this).css('color','yellow');
});
Veera
  • 32,532
  • 36
  • 98
  • 137
0

The proper way is to change 'this' to 'e.target';

$('section').click(function (e) {
    $(e.target).css('color','yellow'); 
});

http://jsfiddle.net/J9kAV/5/

A little more info on why this works. https://developer.mozilla.org/en-US/docs/Web/API/event.target

laymanje
  • 833
  • 5
  • 9