简体   繁体   English

选择除特定子项之外的jquery元素

[英]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. 我针对特定问题修改了JSFiddle

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 : 并且此脚本应返回 ul元素(第一个li除外):

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

Instead, it removes every li. 相反,它将删除每个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/ 内容: http : //jsfiddle.net/LVUMs/13/

Use 采用

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

DEMO DEMO

OR 要么

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

DEMO 2 演示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发挥作用:

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

Here's a fiddle ... 这是一个小提琴 ...

If you're wanting to return a ul element with the removed element inside, try this: 如果要返回一个ul元素,其中包含已删除的元素,请尝试以下操作:

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... 这里是你将如何让新的追加ul元素对身体...

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 请尝试以下JS代码

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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