lakshay lakshay - 20 days ago 8
jQuery Question

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.

Answer

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...
});
Comments