user3877230
user3877230

Reputation: 458

Clicking List-Items with JQuery outputs to many results

I do have a list item which looks like this:

enter image description here

HTML

<ul>
    <li id="nav-menu-item-7" class="menu-element">
        <a href="google.com">TEST 2</a>
        <ul>
            <li id="nav-menu-item-8" class="menu-element">TEST 3</a></li>
            <li id="nav-menu-item-11" class="menu-element">
                PAGE 4
                <ul>
                    <li id="nav-menu-item-77" class="menu-element"><a href="http://google.com" class="menu-link sub-menu-link">LINK</a></li>
                </ul>
            </li>
        </ul>
    </li>
</ul>

JQUERY

$(document).ready(function(){
    $(document).on('click', '.menu-element', function(e){
        var id = $(this).attr('id').replace(/\D/g,'');

        alert(id);
    });
});

I simply want to output the numeric ID of the container in an popup which i achieve with JQuery. The Problem that i am having now it that i get an Popup for the element i clicked and for the parent objects. This means in this case 77,11,7. I only want the first element to be ouput, means the 77 without having to change the whole structure of the menu. Any Ideas? Thank you.

Upvotes: 1

Views: 35

Answers (1)

rupps
rupps

Reputation: 9907

Just stop the event propagation to the parent elements:

  $(document).on('click', '.menu-element', function(e){

        e.stopPropagation();

        var id = $(this).attr('id').replace(/\D/g,'');
        alert(id);
    });

You should read about how events traverse the DOM, first from the document root to the clicked elements, then down to the document object. You can stop the propagation in both phases.

Upvotes: 1

Related Questions