J. Doe
J. Doe

Reputation: 37

Increasing counter does not change value of other variable

why would the [counter] variable value used in other variable not change as the counter value changes? Is it something to do with the reference?

var counter = 0;

var allFields = document.getElementsByClassName('test')[counter].getElementsByClassName("pizza");

console.log(allFields);

counter++;

console.log(allFields); // expected result is to have 2 pizza elements.
<div class="test">
	<div class="pizza"></div>
</div>
<div class="test">
	<div class="pizza"></div>
	<div class="pizza"></div>
</div>
<div class="test">
	<div class="pizza"></div>
	<div class="pizza"></div>
  <div class="pizza"></div>
</div>
<div class="test">
	<div class="pizza"></div>
	<div class="pizza"></div>
  <div class="pizza"></div>
  <div class="pizza"></div>
</div>

Upvotes: 1

Views: 150

Answers (2)

nurdyguy
nurdyguy

Reputation: 2945

As soon as you set

var allFields = document.getElementsByClassName('test')[counter]

the object is created. You cannot then dynamically change the object by just changing counter. If you want to be able to do this then just save

var allFields = document.getElementsByClassName('test')

and use the [counter] when you need.

Upvotes: 1

hsz
hsz

Reputation: 152206

When you've assigned fields to allFields with counter = 0 - they'll not change anymore - you have to reassign this variable again.

I'd suggest you to create it as a function:

var allFields = function(i) {
  return document.getElementsByClassName('test')[counter].getElementsByClassName("pizza");
}

var counter = 0;
console.log(allFields(counter));

counter++;
console.log(allFields(counter));

The other, better way is to make a loop, like:

for (var i = 0, i < 2; i++) {
  var allFields = document.getElementsByClassName('test')[i].getElementsByClassName("pizza");

  console.log(allFields);
}

Upvotes: 2

Related Questions