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

pew*_*ers 1 javascript jquery

有没有办法检查a child div是否是第一项parent div

例如:

<div id="parent">
   Some text                   <--------- not the first thing in the div
   <div id="child"></div>
</div>
Run Code Online (Sandbox Code Playgroud)

要么

<div id="parent">
   <div id="child"></div>      <--------- is the first thing in the div
   Some text
</div>
Run Code Online (Sandbox Code Playgroud)

Aru*_*hny 5

就像是

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

演示:首先,不是

几乎没有条件要检查

  1. 需要测试文本节点所以必须使用.contents()
  2. 由于空文本节点必须单独使用,因此需要使用过滤器来过滤空文本节点