0

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>

2
  • 1
    Why do you need the second loop? Just add the innerHTML in the first loop: var element = document.createElement("option"); element.innerHTML = i; fontSizeBox.appendChild(element); And remove all the code below that. Commented Jan 10, 2023 at 6:41
  • 1
    Also, Array.from(fontSizeBox) does not convert the fontSizeBox to an array. It returns an array which you need to assign to another variable: var fontSizeBoxArray = Array.from(fontSizeBox) Commented Jan 10, 2023 at 6:44

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

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.