1

I'm using jQuery .attr() method to get the value of an element's attribute, in this case an id, and storing it into a string. Then I replace "info" to "article" in the string to hide and show elements in my page.

My HTML code looks like this:

<div id="navigator">
    <div id="info_01"><a href="#">Lorem Ipsum</a>
        <div id="info_02"><a href="#">Lorem Ipsum</a></div>
    </div>
    <div id="info_03"><a href="#">Lorem Ipsum</a></div>
</div>

jQuery code:

    $('#navigator>div, #navigator>div>div').click(function(){
    var variable=$(this).attr('id');
    var variable2=(variable.replace("info", "article"));
    console.log(variable2);

    $("#another_div").hide();
    $("#"+variable2).show();
});

I'm outputting log to console, and when I click on parent divs inside #navigator such as #info_01 and #info_03 it prints only the id of the div I clicked, but when I click on child elements in #navigator such as #info_02, it prints two lines:

article_02
article_01

As you can see, the first one is from the first div I click on, but since I'm also clicking on its parent, it outputs the parent's id.

I only need to output one id, the one from the element I click on, and not its parent's id.

How can I do that?

5
  • This should help quirksmode.org/js/introevents.html. Look for "event propagation". Also I suggest you use a common class instead of id's. Commented Dec 1, 2013 at 21:35
  • i think that the thing you are trying to achieve can be done in a simpler way if explaing clearly what exactly you are trying to do.. Commented Dec 1, 2013 at 21:37
  • Thanks, elclanrs. Useful and simple answer. Commented Dec 1, 2013 at 21:42
  • possible duplicate of Prevent execution of parent event handler Commented Dec 1, 2013 at 21:42
  • To get the id from the element clicked, just use the event.target instead ? Commented Dec 1, 2013 at 21:47

1 Answer 1

2

Use .stopPropagation(). This prevents the event from bubbling up the DOM tree, preventing any parent handlers from being notified of the event. Read more on https://api.jquery.com/event.stoppropagation

$('#navigator>div, #navigator>div>div').click(function(e){
    var variable=$(this).attr('id');
    var variable2=(variable.replace("info", "article"));
    console.log(variable2);

    $("#another_div").hide();
    $("#"+variable2).show();
    // propagate
    e.stopPropagation();
});
Sign up to request clarification or add additional context in comments.

2 Comments

Could you explain why e.stopPropagation() is necessary?
@nueverest stopPropagation() Prevents the event from bubbling up the DOM tree, preventing any parent handlers from being notified of the event. read more on api.jquery.com/event.stoppropagation

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.