0

I was wondering if anyone knows the reason for [i-1] in the fourth line when you also have i++ in the second line? Thank you for any help! (It's from the book "JavaScript" by Vodnik and Gosselin.)

if (figureCount === 3) {

for (var i = 1; i < 4; i++) {
filename = "images/IMG_0" + photoOrder[i] + "sm.jpg";
currentFig = document.getElementsByTagName("img")[i - 1];
currentFig.src = filename;
}//end of for loop

3 Answers 3

2

It because document.getElementsByTagName returns an HTMLCollection(similar to array) hence. So accessing the 1st(and subsequent) img tag on the page are done through setting i-1

Sign up to request clarification or add additional context in comments.

Comments

1

document.getElementsByTagName return a HTMLCollection which is not an array but an array like object. So to access any element from that collection you can pass the index.

document.getElementsByTagName("img")[i - 1] is creating a collection of all the img tags & it is accessing specific element in that collection by passing the index [i-1]

In the below example [1] is trying to access the second element from the collection

var getAllDiv = document.getElementsByTagName('div');
console.log(getAllDiv[1].innerHTML)
<div>1</div>
<div>2</div>

Comments

0

Some developers get confused with the for loop operators logic instead of doing it correctly:

for (var i = 0; i < 3; i++) {

they decided to add some extra processing to the mix ( which isn't that big of a deal ) but iv'e fired developers for less.

CurrentFig is using i - 1 because it appears there is a prepended img element so the developer also chose to select it as well instead of selecting the exact elements that he needs.

1 Comment

While I agree that starting with an i of 0 is more helpful in this instance, could you please add some slight explanation of why this is the case? And also why the subtraction would be needed in currentFig? That would really help improve the quality of your answer :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.