0

I need to check if an element is last child like this

Determining if the element is the last child of its parent

But I use cheerio instead of jquery (for lighter weight) on node.js

https://github.com/MatthewMueller/cheerio

It gave me error:

TypeError: Object XXXXXXX has no method 'is'

Can someone confirm? If so, what is the elegant way to check if a node is last child?

Thanks.

Community
  • 1
  • 1
HP.
  • 19,226
  • 53
  • 154
  • 253

3 Answers3

1

Here's an example which adds an isLastSibling method for checking if an element is the last sibling.

var cheerio = require('cheerio'),
    $ = cheerio.load('<p><a>1</a><b>2</b><i>3</i></p>'),
    $fn = Object.getPrototypeOf($());

$fn.isLastSibling = function() {
    return this.parent().children().last()[0] === this[0];
};

console.log(
    $('a').isLastSibling(),
    $('b').isLastSibling(),
    $('i').isLastSibling()
);

The output you should get is false false true because the <a> and <b> elements are not the last siblings but the <i> element is.

Nathan Wall
  • 10,530
  • 4
  • 24
  • 47
  • Actually, `length` 0 when there is next() and `length` ` when it's last child. I just tested. Strange. Can you confirm? – HP. Feb 28 '13 at 06:11
  • You're right, it didn't work. I have modified my answer with a complete, tested example. – Nathan Wall Feb 28 '13 at 06:31
0

Try

<script type="text/javascript">

    $(function()
    {
        $('dom').each(function()
        {
            var $this = $(this);
            if ( $this === $this.parent().last())
            {
                alert('got me!');
            }
        })
    });

</script>
Dipesh Parmar
  • 27,090
  • 8
  • 61
  • 90
0

Check the jquery version it is using?

You can use last-child-selector for this

For example: $("div span:last-child").css('background','red');

Here is the docs http://api.jquery.com/last-child-selector/

Rohan Kumar
  • 40,431
  • 11
  • 76
  • 106
  • I got the latest here and it doesn't use jQuery (I believe): https://github.com/MatthewMueller/cheerio. `div span:last-child` doesn't work because there are many other `non-span` elements in the `parent` that could be last child. – HP. Feb 28 '13 at 06:31