Use jQuery not() method to select all elements except a certain element

It may be used in daily work to select all elements except a certain or certain elements.

At this time, we can use the not() method in jQuery traversal to exclude certain elements, for example, based on the #id, .class, etc. of the element. The code is as follows:

$("div.content *").not(".keep");

Represents all elements under the div of the .content class except the .keep class;

Also, note that * here means all elements.

Example:

html:

<div class="box">
    <span>点击按钮删除下面绿色框中所有不是keep类的元素,keep类的元素用红色区分。</span>
    <div class="content">
        <input type="checkbox" name="item"><span>萝卜</span>
        <input type="checkbox" name="item"><span>青菜</span>
        <input type="checkbox" name="item" class="keep"><span class="keep">小葱</span>
        <input type="checkbox" name="item" class="keep"><span class="keep">豆腐</span>
        <input type="checkbox" name="item"><span>土豆</span>
        <input type="checkbox" name="item"><span>茄子</span>
        <input type="text" value="我也不是keep类的">
    </div>       
    <input type="button" value="删除">
</div>

css:

.box{
    width:300px;
    height:200px;
    padding:10px 20px;
}
.box>span{
    color:#999;
}
.keep{
    color:red;
}
.content{
    width:250px;
    height:100px;
    margin:10px 0;
    border:1px solid green;
}
input[type='button']{
    width:200px;
    height:35px;
    margin:10px;
    border:2px solid #ebbcbe;
}

jquery:

$(function(){
    $("input:button").click(function() {
        $("div.content *").not(".keep").each(function() { // "*"表示div.content下的所有元素
            $(this).remove();
        });
    });
})

Additional notes:

There are two main ways to use *:

1. Wildcard: represents multiple elements.

For example: .container * represents all elements under .container.

2. Attributes starting with * asterisk in the css selector:

The asterisk + CSS attribute in the CSS selector generally distinguishes the attribute CSS HACK between IE6 and IE8, IE6 and FF, IE7 and IE8, and IE7 and FF browsers. code show as below:

.cont{
    border:1px solid #000;
    width:220px;
    *width:300px;
}

We set two widths, one at 220px and one with an asterisk at 300px. Through testing and comparison of major browsers, we will find that the width is 300px in IE6 and IE7, but the width is 220px in IE8 and above MSIE versions, Google Chrome, and Firefox (FF) browsers.

You can test it yourself to see if the effect is the same as described.

Note: This is the position before and after the asterisk CSS attribute is placed.

Guess you like

Origin blog.csdn.net/u013938578/article/details/135411865