Guado
Guado

Reputation: 13

Getting element attribute with jQuery .attr() method

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?

Upvotes: 1

Views: 168

Answers (1)

Pejman
Pejman

Reputation: 2636

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();
});

Upvotes: 2

Related Questions