Reputation: 1374
I'd like to access several element ids using jQuery, so I can dynamically alter the contents of these elements. However, (I believe) I am unable to use nth-child selectors, as these element ids do not all share the same parent, as they use a table layout.
For example,
<table>
<tr>
<td> <div class="bio"><img id="photograph_1" src="test.jpg"></div> </td>
<td> <div class="bio"><img id="photograph_2" src="test.jpg"></div> </td>
</tr>
<tr>
<td> <div class="bio"><img id="photograph_3" src="test.jpg"></div> </td>
<td> <div class="bio"><img id="photograph_4" src="test.jpg"></div> </td>
</tr>
</table>
I assumed there would be a way to access each element by its id, as $('#photograph_1')
however when I try to do this dynamically it does not work. for(i=0; i++; i<4) { $('#photograph_'+(i+1)).attr('src',image[i]); }
(image[] is an array of image sources).
Is what I am trying to do possible? If so, how can it be done? From this reference, I am not clear what to do.
Upvotes: 0
Views: 33
Reputation: 104785
Your for loop will work fine, you're forgetting the #
in your selector. Try
for(i=1; i <= 4; i++) { $('#photograph_'+i).attr('src',image[i]); }
Upvotes: 1