I want to create a 2d array from divs with classes within divs with classes. This code gives me an array as far as I understood, but I can't access my objects in the array, whats wrong?
var frames;
var myElements = [];
var animatedClasses = ["text", "splash"];
for (var i = 0; i < frames.length; i++) {
for (var j = 0; j < animatedClasses.length; j++) {
myElements[[i], [i, [j]]] = frames[i].getElementsByClassName(animatedClasses[j]);
}
}
myElements[0,0].style.opacity = "0.5"; // DOESN'T WORK
}
<div class="frame">
<div class="splash"></div>
<div class="text"></div>
</div>
<div class="frame">
<div class="splash"></div>
<div class="text"></div>
</div>
31piy
23.9k6 gold badges51 silver badges69 bronze badges
1 Answer 1
You can try the following code
var frames = document.getElementsByClassName('frame');
var myElements = [];
var animatedClasses = ["text", "splash"];
for (var i = 0; i < frames.length; i++) {
if(!myElements[i]) myElements[i] = Array(animatedClasses.length);
for (var j = 0; j < animatedClasses.length; j++) {
myElements[i][j] = frames[i].getElementsByClassName(animatedClasses[j])[0];
}
}
console.log(myElements);
myElements[0][1].style.opacity = "0.5"; // DOESN'T WORK
myElements[0][1].style.color = "red";
<div class="frame">
<div class="splash"> Hello</div>
<div class="text"></div>
</div>
<div class="frame">
<div class="splash"></div>
<div class="text"></div>
</div>
answered Jun 16, 2018 at 13:51
Md Johirul Islam
5,1924 gold badges28 silver badges57 bronze badges
Sign up to request clarification or add additional context in comments.
1 Comment
Alf
perfect! Thanks a lot!
default
myElements[[i], [i, [j]]]I believe you can't do this in javascript. The comma operator should return the last (right) element and ignore the first one. And why is thatjsurrounded in[]? Instead of all this, trymyElements[i][j].