Search code examples
jqueryhtmlpreventdefault

preventDefault(); jquery child affected


I checked answer about that but couldn't adapt a solution so need your help. I'd like the preventdefault(); works only to parents element but here it works for everything

<ul class="links">
        <li><a href="#"><b>Accueil</b></a></li>
        <li>
            <a href="#"><b>Liste serveurs</b></a>
                <ul class="sub">
                    <li><a href="#"><b>sub 1</b></a></li>
                    <li><a href="#"><b>sub 2</b></a></li>
                </ul>
        </li>
</ul>

JS

$('.links > li').on('click',function(noway) {
        noway.preventDefault();

});

Goal is when I click on Liste serveurs, .sub appear, but here when I click on sub 1, nothing happened. I'd like to go to the sub 1 link.

EDIT: I don't get it, I feel it is totally wrong, but it works.

$('.links > li').on('click',function(noway) {
            if($(this).attr("class") === "sub") { noway.preventDefault(); }

    });

Solution

  • Try the most basic way....why making it complex!!

    $('ul.links > li > a').click(function(event ) {
            event.preventDefault();
    });
    

    demo

    Meaning :

    preventDefault() only for direct descendant a of li and this li should be direct descendant of ul.links