Mohammed
Mohammed

Reputation: 45

Making a loop over an array and only add even numbers to it

The idea of the program is to make a loop that will iterate over the option elements in the select box and only add even numbers to it (from 16 to 30 including 30). To be specific : It is a fontSizeBox and I want to add font sizes to it so the user can choose from them .

The problem is that I get numbers starting from 16 to 23 and not as expected . The code :

window.onload = function() {
  let fontSizeBox = document.createElement("select");
  fontSizeBox.name = "fontSize-box";
  document.body.prepend(fontSizeBox);

  let fontSizeBoxLabel = document.createElement("label");
  fontSizeBoxLabel.appendChild(document.createTextNode("Choose the font size :"));
  fontSizeBox.before(fontSizeBoxLabel);

  for (let i = 16; i <= 30; i += 2) {
    fontSizeBox.appendChild(document.createElement("option"));
  }
  
  Array.from(fontSizeBox);
  /* The above code will make the fontSizeBox an array so I can iterate over
  it using the loop */
  for (let i = 0; i <= 7; i++) {
    fontSizeBox[i].innerHTML = i + 16;
    /* The following code won't work without the number constructor 
    because I tried this code in the console and here is the output: 

    typeof fontSizeBox[0].innerHTML;
    >> 'string' */
    if ((Number(fontSizeBox[i].innerHTML) % 2) !== 0) {
      continue;
    }
  }

}
<title>Document</title>

Upvotes: 0

Views: 129

Answers (1)

Carsten Massmann
Carsten Massmann

Reputation: 28196

Maybe this will do it for you?

window.onload = function() {
  document.body.insertAdjacentHTML("afterbegin",`<label>Choose the font size: <select name="fontSize-box">${[...Array(8)].map((_,i)=>`<option>${2*i+16}</option>`).join("")}</select></label>`);
}
<title>Document</title>

I decided to use .insertAdjacentHTML(), and only once, as every modification of the DOM will be costly in terms of browser activity. While the .createElement() and .appendChild() calls are fast and efficient in themselves, doing everything in one go will probably be more efficient in the end than the multiple create and append actions.

Upvotes: 1

Related Questions