简体   繁体   中英

Select jquery elements except specific children

This is a simple question, but, I haven't found a clear answer in any of the question that I found. I modified a JSFiddle for my specific question.

I got this tiny code:

<ul>
    <li id='one'>Element 1</li>
    <li id='two'>Element 2</li>
    <li id='three'>Element 3</li>
    <li id='four'>Element 4</li>
    <li id='five'>Element 5</li>
</ul>

and this script should return the ul element excepting the first li :

$(function(){
    $("ul").not($('#one'))
});

Instead, it removes every li. What have I done wrong?

EDIT: In others words, I would like a selector which selects this, without removing the actual element (= inside a variable)

<ul>
    <li id='two'>Element 2</li>
    <li id='three'>Element 3</li>
    <li id='four'>Element 4</li>
    <li id='five'>Element 5</li>
</ul>

FIDDLE: http://jsfiddle.net/LVUMs/13/

Use

 $("ul li").not($('#one')).remove(); 

DEMO

OR

 $("ul li:not(#one)").remove(); 

DEMO 2

EDIT

You need

 var ulexceptOneLi = $("ul li:not(#one)"); 

or

 var ulexceptOneLi = $("ul li").not($('#one')); 

Try this code:

Fiddle

$(function(){
    $("ul>li").not($('#one')).empty();
});

Assuming you meant to keep the ul in play:

$("ul li#one").remove();

Here's a fiddle ...

If you're wanting to return a ul element with the removed element inside, try this:

function do_crazy_thing(){

  var removed = $("ul li#one").remove();

  return $('<ul></ul>').append(removed);

}

do_crazy_thing();

Here's another fiddle ...

Here's how you would then append your new ul element to the body...

Demo Fiddle

According to your question, your expected output is :

<ul>
    <li id='two'>Element 2</li>
    <li id='three'>Element 3</li>
    <li id='four'>Element 4</li>
    <li id='five'>Element 5</li>
</ul>

Check the demo.

Edit :

$(function(){
    var removed = $("ul li:not(#one)");
});

OR

var op = $("ul :not(#one)");

Please try below JS code

$(function(){
   var test= $("ul li").remove("#one");
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM