pewpewlasers
pewpewlasers

Reputation: 3215

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>

Upvotes: 1

Views: 37

Answers (1)

Arun P Johny
Arun P Johny

Reputation: 388316

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

Upvotes: 5

Related Questions