title: Using knockout to determine the first element in a foreach
body: <p>In a knockout template binding process, I need to detect when I am processing the first element in each row as it should not have the anchor tag surrounding it.</p>
  
  <p>Given the following js for knockout...</p>
  
  <pre><code>function Model() {
      var self = this;
      self.gridData = ko.observableArray('{"GridData":[["Category foo","0","0"],["Category bar","0","0"]]}');
  }
  
  var model = new Model();
  ko.applyBindings(model);
  </code></pre>
  
  <p>and this template...</p>
  
  <pre><code>&lt;script type="text/html" id="template"&gt;
      &lt;table&gt;
          &lt;tbody data-bind="foreach: gridData"&gt;
              &lt;tr data-bind="foreach: $data"&gt;
                  &lt;td&gt;&lt;a href="" data-bind="text: $data"&gt;&lt;/a&gt;&lt;/td&gt;
              &lt;/tr&gt;
          &lt;/tbody&gt;
      &lt;/table&gt;
  &lt;/script&gt;
  </code></pre>
  
  <p>and this html...</p>
  
  <pre><code>&lt;div data-bind="template: { name: 'template' }"&gt;&lt;/div&gt;
  </code></pre>
  
  <p>Can the 'if' binding be used in some way that runs true if we are processing the 1st element?</p>
  
  <p>Also, I found this <a href="https://stackoverflow.com/questions/5371772/knockout-js-foreach-but-with-a-special-element-first">SO Post</a>, but it doesn't get me quite what I am looking for.</p>
  
  <p><strong>UPDATE:</strong></p>
  
  <p>Thanks for both answers. Using the info provided in each, I was able to find a good solution for my situation.  I updated my template to the below...</p>
  
  <pre><code>&lt;script type="text/html" id="template"&gt;
          &lt;tbody data-bind="foreach: gridData"&gt;
              &lt;tr data-bind="foreach: $data"&gt;
                  &lt;!-- ko if:($index()===0) --&gt;
                  &lt;td data-bind="text: $data"&gt;&lt;/td&gt;
                  &lt;!-- /ko --&gt;
                  &lt;!-- ko ifnot:($index()===0) --&gt;
                  &lt;td&gt;&lt;a href="" data-bind="text: $data"&gt;&lt;/a&gt;&lt;/td&gt;
                  &lt;!-- /ko --&gt;
              &lt;/tr&gt;
          &lt;/tbody&gt;
  &lt;/script&gt;
  </code></pre>