Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to simplify document.getElementById?

My javascript code is exceeding 3000 thousand lines of code because I need to call many variables, is there any way to simplify this?

Here's the code:

var Start = document.getElementById('Start'),
    question1 = document.getElementById('1'),
    question2 = document.getElementById('2'),
    question3 = document.getElementById('3'),
    question4 = document.getElementById('4'),
    question5 = document.getElementById('5'),
    question6 = document.getElementById('6'),
    question7 = document.getElementById('7');

I have more than 50 variables to questions and more 50 to answers.

like image 808
TonyCrudor Avatar asked Sep 16 '25 13:09

TonyCrudor


2 Answers

Simply use a single array variable for keeping all questions instead of individual variables:

// initialize a variable to be an empty array
var questions = [];

// create a loop which assigns value 1 to 9 into the variable i
for (let i = 1; i < 10; i++) {
    // assign the content of the element with ID i to i-th element of the array
    questions[i] = document.getElementById(i);
}

Then, you can use for example questions[5] instead of question5.

In case you have a non-sequential naming of HTML elements, you may use an array containing a list of element IDs:

// define a list of element IDs
let htmlIds = ['id1', 'ab', 'xy', 'anotherId'];

// initialize a variable to be an empty array
var questions = [];

// go through all items of the htmlIds arrays and populate questions
htmlIds.forEach(item => questions[item] = item);

But I would consider a different approach in such case, you can ignore the IDs and query the questions for example using a class as PHP Guru mentions in his answer.

like image 106
David Ferenczy Rogožan Avatar answered Sep 19 '25 01:09

David Ferenczy Rogožan


As mentioned, you can use a loop and an array:

let questions = [];
for (let i = 0; i < 8; ++i) {
  questions.push(document.getElementById(i));
}

You loop through a certain suitable range -- and append to the array in each iteration.

Then, you can access a particular "question" like this:

console.log(questions[4]);
like image 36
costaparas Avatar answered Sep 19 '25 03:09

costaparas