Search code examples
javascriptjquerywordpressparentpreventdefault

Prevent default on link if parent hasClass()


Simplified HTML:

<ul>
    <li class="no-link"><a>Should not be clickable</a>
        <ul>
            <li><a>Should be clickable</a></li>
            <li><a>Should be clickable</a></li>
        </ul>
    </li>
</ul>

Javascript:

jQuery(document).ready(function( $ ) {

    $('a').parent().click(function(e) {
        if($(this).hasClass('no-link')){
            e.preventDefault();
        }
    });
})

Works fine on the link that should not be clickable, but also affects the two descendant a tags. Why? I thought parent() only traversed up a single step in the DOM.

I'm adding the class programatically via WordPress (as an option in the Appearance > Menus control panel), so targeting the a tag directly via class is not really an option.


Solution

  • What you want is to actually capture the click on a element and then check for parent class inside it.

    Just change your code to:

    $('a').click(function(e) {
         if($(this).parent().hasClass('no-link')){
             e.preventDefault();
         }
    });