Knockout.js – foreach binding – test if last element

I’ve simplified the problem, but this jsFiddle demonstrates a possible solution.

“if” binding:

<div data-bind="if: ($index() === ($parent.data().length - 1))">I'm the last element</div>

Containerless “if” binding:

<!-- ko if: ($index() === ($parent.data().length - 1)) -->
<div>I'm the last element again</div>
<!-- /ko -->

You can use $index within a foreach binding to get the index of the currently bound item. Use that to compare against the original collection of the parent.

See HERE for more information regarding binding contexts.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)