简体   繁体   English

使用jQuery检查某个元素是否是另一个元素中的第一件事

[英]Check, with jQuery, if an element is the first thing in another element

Is there a way to check if a child div is the first item of the parent div ? 有没有一种方法可以检查child div是否是parent div的第一项?

For example: 例如:

<div id="parent">
   Some text                   <--------- not the first thing in the div
   <div id="child"></div>
</div>

Or 要么

<div id="parent">
   <div id="child"></div>      <--------- is the first thing in the div
   Some text
</div>

Something like 就像是

var isFirst = $('#child').is($('#parent').contents().filter(function () {
    return this.nodeType != 3 || $.trim(this.nodeValue) != ''
}).first())

Demo: First , Not 演示: 第一不是

There are few conditions to check 需要检查的条件很少

  1. need to test text nodes so have to use .contents() 需要测试文本节点,因此必须使用.contents()
  2. since empty text nodes has to be left alone need to use filter to filter empty text nodes out 由于必须将空文本节点留空,因此需要使用过滤器将空文本节点过滤掉

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

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