0

This is what I'm trying to accomplish:

var result = document.getElementById("o_q1_op1");
document.getElementById("a1_op1").style.height = result.scrollHeight;

But I dont want to rewrite it a dozen times, instead want to use arrays structured like this:

var que = ["o_q1_op1", "o_q1_op2", "o_q2_op3"];
var ans = ["a1_op1","a1_op2","a1_op3","a1_op4"];

This is what I have so Far:

var que = ["o_q1_op1", "o_q1_op2", "o_q2_op3"];
var ans = ["a1_op1","a1_op2","a1_op3","a1_op4"];
var result;
var index;
var text = "";
for (index = 0; index < que.length; index++) {
    text += que[index];
    var result[index] = document.getElementById(text);
}

var index2;
var text2 = "";
for (index2 = 0; index2 < ans.length; index2++) {
    text2 += ans[index2];
    document.getElementById(text2).style.height = result[index].scrollHeight;
}

I'v never used 2 arrays to accomplish one task before so I'm not sure how to go about it.

3 Answers 3

3

You might like to not use 2 arrays, and instead have one array that ties the two properties together:

var arr = [
             { q:"o_q1_op1",a:"a1_op1"},
             { q:"o_q1_op2",a:"a1_op2"}
          ];

and then the code becomes much simpler, and you never have to deal with the 2 arrays becoming different lengths

for(var i=0;i<arr.length;i++){
    var result = document.getElementById(arr[i].q);
    document.getElementById(arr[i].a).style.height = result.scrollHeight;
}
Sign up to request clarification or add additional context in comments.

1 Comment

indeed, properties is way safer.
1

So long as the two arrays are ordered and remain the same length...

for(var i=0;i< que.length;i++){
    document.getElementById(ans[i]).style.height = 
    document.getElementById(que[i]).scrollHeight;
}

Comments

1

well the += is wrong because it concatinates string

change and simplify code to

var que = ["o_q1_op1", "o_q1_op2", "o_q2_op3"];
var ans = ["a1_op1","a1_op2","a1_op3","a1_op4"];
var result=[];

for (var index = 0; index < que.length; index++) {
    result[index] = document.getElementById(que[index]);
}


for (var index2 = 0; index2 < ans.length; index2++) {
    document.getElementById(ans[index2]).style.height = result[index].scrollHeight;
}

Comments

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.