title: Loop through array, assign each value to an element attribute in Javascript / Jquery
body: <p>I have an array: 'imageIds': </p>
  
  <pre><code>imageIds = ["778", "779", "780", "781", "782"];
  </code></pre>
  
  <p>I want to find all elements of class .preview-image on the page, of which I know the number will match the length of the array.</p>
  
  <p>I then want to assign the first matching element a data attribute 'data-img-id' with the value of imageIds[0], the second matching element with imageIds[1] etc.</p>
  
  <p>So the end result would be converting this:</p>
  
  <pre><code>&lt;div class="preview-image"&gt;...&lt;/div&gt;
  &lt;div class="preview-image"&gt;...&lt;/div&gt;
  &lt;div class="preview-image"&gt;...&lt;/div&gt; etc
  </code></pre>
  
  <p>in to this:</p>
  
  <pre><code>&lt;div class="preview-image" data-img-id="778"&gt;...&lt;/div&gt;
  &lt;div class="preview-image" data-img-id="779"&gt;...&lt;/div&gt;
  &lt;div class="preview-image" data-img-id="780"&gt;...&lt;/div&gt; etc
  </code></pre>
  
  <p>Not quite sure how to form the loop that would achieve this. </p>