sidney
sidney

Reputation: 2714

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/

Upvotes: 2

Views: 60

Answers (5)

Yogesh Sharma
Yogesh Sharma

Reputation: 2017

Please try below JS code

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

Upvotes: 0

Shaunak D
Shaunak D

Reputation: 20626

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)");

Upvotes: 0

Satpal
Satpal

Reputation: 133403

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'));

Upvotes: 3

shennan
shennan

Reputation: 11656

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...

Upvotes: 0

Manoj
Manoj

Reputation: 1890

Try this code:

Fiddle

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

Upvotes: 0

Related Questions