选择具有ID的父级的第一个子级以外的所有子级,然后应用操作

Selecting all but the first child of parent with an ID and then applying action

本文关键字:然后 应用 操作 第一个 ID 选择      更新时间:2023-09-26

我想用jQuery选择父元素的所有子元素(第一个除外),我有以下内容。。

$("li:not(:first-child)");

但我不确定如何将其应用于特定的父ID,这样的方法可行吗?

$('#myID').("li:not(:first-child)");

如果是这样,那么我想在相应的<li>标记之前添加一个元素。那我能用吗?

$('#myID').("li:not(:first-child)").before('<li>Test</li>');

我猜上面有些地方出了问题,因为它不起作用。

关闭,只需传入选择器上下文:

$("li:not(:first-child)", "#myID")

http://api.jquery.com/jQuery/

jQuery( selector [, context] )
selector: A string containing a selector expression
context: A DOM Element, Document, or jQuery to use as context

编辑:我最初的回答假设你在孩子的li中没有更多的li。如果你严格只想选择孩子,请使用>:

$("#myID > li:not(:first-child)") 

有不同的解决方案:

$("li:not(:first-child)", "#myID"); // see @SiGanteng answer
$("#myID li:not(:first-child)");
$("#myID").find("li:not(:first-child)");

简单:使用:gt()帮助选择器:

就像:演示小提琴

$("#myID li:gt(0)").before('<li>Test</li>');

如果你关心速度:):

$("#myID").find("li:gt(0)").before('<li>Test</li>');

或类似:演示小提琴

$("#myID li:not(:first-child)").before('<li>Test</li>');

假设#myIDulol元素,获取所有子元素的另一种可能方法是

$('#myID').children().slice(1)