如何检查元素是否不是第一个子元素?

36

如何判断当前元素不是第一个子元素?

例如,可以使用$(this)来实现:

$("li").click(function(e) {
    if (/* $(this) is not the first-child */)
    {
        /* do something */
    }
});
11个回答

68
您可以使用如下代码测试一个元素是否为其父元素的第一个子元素:$(this).is(':first-child')。其他选择器如 :last-child 也可使用。

4
这将对所有内容返回“true”…… :first 将检查它是否是 jQuery 集合中的第一个项目,我认为你可能想要使用 :first-child - gnarf
13
另外,.not(':first-child') 仍会返回一个 jQuery 集合,而不是一个布尔值... 可以使用 .is(':not(:first-child)') 来实现... - gnarf
3
当@WorkingHard询问“不是”第一个子元素时,该解决方案返回该元素是否为第一个子元素。没有提到@gnarf基本上已经给出了所有的答案。我希望@gnarf回答这个问题,SO用户不要投票支持错误的答案(即使该答案至少获得了3分)。 - Mariano Desanze
将其转换为 “不是” 只需要添加 ! 运算符即可。 - slikts
耸肩 我进行了评论,以便他可以使他的答案更好(或者至少是正确的;)) - gnarf
顺便说一下,这会将当前结果集与文档中的所有第一个子元素进行交叉。 - Ja͢ck

30
你可以简单地询问它相对于其兄弟节点的.index()位置。
$(this).index();   // returns a zero based index position

6
有趣的是,.index()会返回第一个子元素的索引0,这是假的,而其他任何值都是真的,因此,实际上,.index()对于除第一个子元素以外的任何元素都会返回true...完美的答案。 - gnarf
1
我认为这更多是.index()的副作用,但确实是一个不错的观察。 - Stephan Muller
不确定我是否在jQuery中发现了一个错误,但我有一些代码执行parentDiv.parent('td'),在firebug中可以看到它包含1个元素。parentDiv.parent('td').size()为1,但parentDiv.parent('td').index()返回-1。有人知道原因吗? - B T
这是一个非常好的测试项目是否不是第一个的方法。谢谢!如果 ($(this).index()) { //那么它就不是第一个} - Jake

12

5
此外,您可以检查$(this).prev().length是否被定义,例如:
if (!$(this).prev().length){ //This means $(this is the first child
    //do stuff
}

非常好,我认为它最易读,并且与我的其他实现相匹配。使用 .size() 代替 length。 - Andrew

4
如果您想选择除第一个子元素以外的所有内容,可以按照以下步骤进行:
$('#some-parent').children().not(':first')

3

检查索引

$(this).index() == 0 // is first

2

对于想要使用纯JS解决方案的人:

<div id="parent">
  <div id="child-1"></div>
  <div id="child-2"></div>
  <div id="child-3"></div>
</div>

let element = document.getElementById('child-1');
console.log(element.parentElement.firstElementChild === element); // true
console.log(element.parentElement.lastElementChild === element);  // false

element = document.getElementById('child-2');
console.log(element.parentElement.firstElementChild === element); // false
console.log(element.parentElement.lastElementChild === element);  // false

element = document.getElementById('child-3');
console.log(element.parentElement.firstElementChild === element); // false
console.log(element.parentElement.lastElementChild === element);  // true

虽然不够优雅,但它能完成工作。

您甚至可以以相同的方式检查它是否为第n个元素。

let n = 2; // check if it's the 2nd child

let element = document.getElementById('child-2');
// index starts at 0
console.log(element.parentElement.children[-1 + n] === element); // true

2

保持简单,使用DOM


$("li").click(function(e) {

    if (this.previousSibling != null)
    {
        /* do something */
    }

});

0

0

jQuery .not()

jQuery .not()

是一个 jQuery 的函数,它用于从匹配的元素集合中删除指定的元素。在编写 JavaScript 代码时,使用这个函数可以更加方便地操作 DOM 元素,提高开发效率。
$(this).not(':first');

1
:first 不同于 :first-child,使用 .not(':first') 将会从集合中移除第一个项目。 - user113716

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接