0

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
asked Jun 16, 2018 at 13:40
5
  • What is your final goal. Why are you trying to build this structure? Commented Jun 16, 2018 at 13:46
  • 2
    @Alf - You cant just demand answers. The language you are using is demanding. Remember we are here to help you not serve you. Please request not demand. Please see here on how to ask questions. Commented Jun 16, 2018 at 13:47
  • 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 that j surrounded in []? Instead of all this, try myElements[i][j]. Commented Jun 16, 2018 at 13:48
  • Also, what isn't working? Feel free to post an error. We'll help you when you show more effort Commented Jun 16, 2018 at 13:50
  • Sorry if my language was demanding, I didn't do that on purpose. Commented Jun 16, 2018 at 13:59

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

1 Comment

perfect! Thanks a lot!

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.