문제

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.

도움이 되었습니까?

해결책

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.

다른 팁

Try

<script type="text/javascript">

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

</script>

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/

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top