JQuery :Not() Selector Example

 

It’s been a while since I wrote about JQuery. I am spending most of my time these days on backend technologies. Recently while working on a typical requirement on UI, I had to play with some tricky JQuery selectors.

Typically, most of the times we uses JQuery’s class selectors or id selectors for example:

$('#someid').hide();
$('div#container').css('height', '100%');
 
$('.someclass').hide();
$('div.entry').css('height', '100%');

But recently I had a requirement where I had to select all the elements from DOM and ignore a certain one. Consider following example:

In below table, we have checkboxes at each row level. Also there a checkbox to “select all” in header.
jquery-multiple-selector-not-class

Also consider each checkbox has different class and id. Thus it is not possible to select all the row’s checkboxes and ignore ‘select all’ checkbox.

jQuery :not() Selector

In scenario like above and many others, JQuery’s :not() selector comes quite handy. It helps in filtering certain conditions from your selector query. It simple means “Selects all elements that do not match the given selector”.

Consider below table, we have few rows with checkboxes. On select of the checkbox the row background color is highlighted. We simply uses $('input[type=checkbox]') to select checkbox and add click event. But that selects the “select all” checkbox too!

$('input[type=checkbox]').click(function() {
    if(this.checked == true) {
        $(this).parent().parent().addClass('selected');
    } else {
        $(this).parent().parent().removeClass('selected');
    }
});

When clicking “select all” checkbox in above table, the row is highlighted. Now lets see how not()selector can be used here to ignore “select all” checkbox from the selection list.

Now check the below demo with not() selector.

$('input[type=checkbox]:not("#selectall")').click(function() {
    if(this.checked == true) {
        $(this).parent().parent().addClass('selected');
    } else {
        $(this).parent().parent().removeClass('selected');
    }
});

Check the above HTML table, on clicking “select all” no rows are highlighted! This is because we used$('input[type=checkbox]:not("#selectall")') to select the checkboxes.

not() can be combined with most of the jQuery selectors to form powerful queries that can be difficult to achieve. Following are few examples:

  • :not('.cssclass') – Ignores all the elements with class=”cssclass” from the selected list
  • :not('#someid') – Ignores the element with id=”someid” from the selected list
  • :not('first-child') – Ignores the first child from the selected list
  • :not('only-child') – Ignores all the elements that are only child of their parents from the selected list
  • :not(':eq(n)') – Ignores the nth element from the selected list
  • :not(':even') – Ignores all even elements from the selected list

Hope this is useful.

原文地址:https://www.cnblogs.com/hephec/p/4574467.html