简体   繁体   中英

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 ?

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()
  2. since empty text nodes has to be left alone need to use filter to filter empty text nodes out

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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