Eilidh
Eilidh

Reputation: 1374

How can I access (in effect) 'an array' of element ids through jQuery? i.e. #photograph_1 #photograph_2

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

Answers (2)

tymeJV
tymeJV

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

wirey00
wirey00

Reputation: 33661

fix your for statement

it should be

for (var i = 0;i < 4; i++ ) 

not

for(i=0; i++; i<4) 

MDN Docs

for ([initialization]; [condition]; [final-expression])

statement

You were using i++ as the condition

Upvotes: 2

Related Questions