Skip to content Skip to sidebar Skip to footer

Prevent Default On Link If Parent Hasclass()

Solution 1:

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

Solution 2:

    $('li > a').click(function(e) {
        if($(this).parent().hasClass('no-link')){
            console.log('parent has class no-link')
            e.preventDefault()
        }
    });
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><ul><liclass="no-link"><ahref="#">Should not be clickable</a><ul><li><ahref="#">Should be clickable</a></li><li><ahref="#">Should be clickable</a></li></ul></li></ul>

Solution 3:

"I thought parent() only traversed up a single step in the DOM."

It does. But you are attaching your click handler to the parent, and click events bubble up from the clicked item through their parent, the parent's parent, etc., and can be cancelled anywhere along that chain. So your code cancel all clicks for all anchors within that parent element.

Try this instead:

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

That is, handle the click event at the anchor level, testing the parent of the clicked item.

Solution 4:

Simple solution is the best - just stop propagation:

jQuery(document).ready(function( $ ) {
    $('a').parent().click(function(e) {
        e.stopPropagation(); // Preventing from event bubbling and capturingif($(this).hasClass('no-link')){
            e.preventDefault();
        }
    });
})

Post a Comment for "Prevent Default On Link If Parent Hasclass()"