abhit
abhit

Reputation: 981

How to select parent element with a particular class in jQuery?

I have the following element structure.

<ul class="pagination floatRight margin-top-3x margin-right-2x search-pagination-cntr" id="logs_link_pager"><li class="hide disabled"><a href="/marketing/videoCall/history/businessID/f1f0e0d3-4e47-ba1a-1d57-5f9d009a41db"></a></li>
    <li class="previous disabled"><a href="/marketing/videoCall/history/businessID/f1f0e0d3-4e47-ba1a-1d57-5f9d009a41db"><span aria-hidden="true" class="p0">« Previous</span></a></li>
    <li class="active"><a href="/marketing/videoCall/history/businessID/f1f0e0d3-4e47-ba1a-1d57-5f9d009a41db">1</a></li>
    <li class=""><a href="/marketing/videoCall/history/businessID/f1f0e0d3-4e47-ba1a-1d57-5f9d009a41db/page/2">2</a></li>
    <li class="next"><a href="/marketing/videoCall/history/businessID/f1f0e0d3-4e47-ba1a-1d57-5f9d009a41db/page/2"><span aria-hidden="true">Next »</span></a></li>
    <li class="hide"><a href="/marketing/videoCall/history/businessID/f1f0e0d3-4e47-ba1a-1d57-5f9d009a41db/page/2"></a></li>
</ul>

Now I want to write a click event such as

$('#logs_link_pager a').click(function(ev)

but I do not want the click event for those <a> elements whose parent <li> element have either active or disabled class.

Upvotes: 1

Views: 460

Answers (3)

pranav-dev
pranav-dev

Reputation: 68

No need of JS for removing click event of link.

If you want to remove the click for links whose li has class disabled or active then write below css-:

#logs_link_pager li.disabled a,
#logs_link_pager li.active a{
    pointer-events: none;
}

This will disable links whose parent li has disabled and active classes. You can also add css to highlight them to show as active or disabled.

Upvotes: 0

Samir
Samir

Reputation: 1368

You can also use .parents() to find the parents,

$('#logs_link_pager a').click(function(ev) {

   if ($(this).parents('li').hasClass('active')) 

   // Rest of the code...

});

Upvotes: 0

Rory McCrossan
Rory McCrossan

Reputation: 337550

You can use :not in the selector:

$('#logs_link_pager li:not(.active, .disabled) a').click(function(ev) {
    // your code here...
});

Alternatively you can check the class of the parent within the click handler itself. This approach would be better if the active and disabled classes are dynamically changed:

$('#logs_link_pager a').click(function(ev) {
    if ($(this).closest('li').is('.active, .disabled')) 
        return;

    // your code here...
});

Upvotes: 4

Related Questions