-3

Hi All
First data:

    let NewDivForGame_0 = document.createElement('div');
    let NewDivForGame_1 = document.createElement('div');
    let NewDivForGame_2 = document.createElement('div');

and so on...12
Next:

  NewDivForGame_0.id = 'Key';
        NewDivForGame_1.id = 'string_1';
            NewDivForGame_2.id = '1a1';

and so on...12
Next: append.
Next:

   for (i=0;i<=12;i++){
       document.getElementById("NewDivForGame_"+i.id).style.width ="35px"; //ERROR
       document.getElementById("NewDivForGame_"+[i].id).style.height= "35px"; //ERROR
       document.getElementById("NewDivForGame_"+[i].id).style.backgroundColor = "blue";
       console.log('Create size div run #'+i);

It doesn't work. Help me please. Please write a solution.

tried:
1)document.getElementById("NewDivForGame_"+i.id).style.width = "35px"; //ERROR 2)document.getElementById("NewDivForGame_"+[i].id).style.width = "35px"; //ERROR
3)

let DetectPer = "NewDivForGame_";
document.getElementById(DetectPer+i.id).style.width = "35px"; //ERROR

It doesn't work. Help me please. Please write a solution.

KimL
  • 1
  • 2
  • Does it give a specific error message? If so please post it – jop frenken Nov 11 '22 at 07:35
  • Try to append it to the document first. I dont think you can edit the style if it doesn't exist on the DOM. – jop frenken Nov 11 '22 at 07:42
  • Did you append the elements to the DOM? You can't use `getElementById` on "stuff" that isn't in the DOM. – Bqardi Nov 11 '22 at 07:42
  • Welcome to Stack Overflow! Please post a [mcve] of your attempt, noting input and expected output using the [\[<>\]](https://meta.stackoverflow.com/questions/358992/ive-been-told-to-create-a-runnable-example-with-stack-snippets-how-do-i-do) snippet editor. – mplungjan Nov 11 '22 at 07:47
  • If you had posted a [mcve] with relevant HTML and CSS, then I could explain my solution better. I am sure the solution is trivial if you use CSS and a class instead of JS generated styles – mplungjan Nov 11 '22 at 09:55

3 Answers3

1

You cannot build your selectors like that - it is wishful thinking. To do what you are trying you would need eval, or worse:

window["NewDivForGame_"+i].id

Neither which are recommended

Why not access them using querySelectorAll, here I find all elements where the id starts with NewDivForGame

document.querySelectorAll("[id^=NewDivForGame]").forEach(div => {
  div.style.width ="35px"; 
  div.style.height= "35px"; //ERROR
  div.style.backgroundColor = "blue";
})

or use css and a class

.blueStyle { 
  width: 35px;      
  height: 35px;
  background-color: blue;
}

and do

 NewDivForGame.classList.add("blueStyle") 

or

document.querySelectorAll("[id^=NewDivForGame]").forEach(div => div.classList.add("blueStyle"))
mplungjan
  • 169,008
  • 28
  • 173
  • 236
1

Another example, maybe not so short as then one of @mplungjan, but it shows how it can be done differently.

If You want to create elements you can use simple for loop to do it, but then you need to add them to DOM as a child of other DOM element. In example below I've added first 'div' as a child of body, second as child of first and so on.

Because all elements references where stored in newDivForGame array we can use it to change style properties using simple for loop.

{
  const newDivForGame = [];
  for (let i = 0; i < 12; ++i) {
      newDivForGame.push(document.createElement('div'));
      newDivForGame[i].id = `key${i}`;
      document.body.appendChild(newDivForGame[I]);
  }

  for (const elem of newDivForGame) {
      elem.style.width = '35px';
      elem.style.height = '35px';
      elem.style.background = 'blue';
  }
}
eRtuSa
  • 46
  • 5
0

The main problems with your code are these lines:

   for (i=0;i<=12;i++){
       document.getElementById("NewDivForGame_"+i.id).style.width ="35px"; //ERROR
       document.getElementById("NewDivForGame_"+[i].id).style.height= "35px"; //ERROR
       document.getElementById("NewDivForGame_"+[i].id).style.backgroundColor = "blue";
       console.log('Create size div run #'+i);
   ...

From what I can tell, you're attempting to access your variables by expecting your browser to evaluate the result of concatenating a string with a number.

Aside from that, you're attempting to access the id property from i, which as it stands, is a number. The number primitive does not have an id property, but based on your code it seems you might have been mixing it up with your string/eval assumption.

Lastly, your line of [i] was actually creating an array with the number i being the single and only element. Arrays likewise do not have an id property.

(Un)Fortunately, Javascript doesn't work this way. At least not exactly that way; in order for the browser or container to do what you expect, there's a few methods that could be used, but I'm only going to reference two; the dreaded eval(), which I won't get into due it being a dangerous practice, and an object literal definition. There are of course other ways, such as the other existing answer(s) here, but:

// Here, we define an object literal and assign it properties for each div manually.
let gameDivs = {
  NewDivForGame_0: document.createElement('div'),
  NewDivForGame_1: document.createElement('div'),
  // etc
};

// And then assign the id values sort of like you do in your question;
gameDivs.NewDivForGame_0.id = 'Key';
gameDivs.NewDivForGame_1.id = 'string_1';
gameDivs.NewDivForGame_2.id = '1a1';
// etc

for (i=0;i<=12;i++){
       // Before finally using square bracket notation to target the
       // properties by a dynamic name;
       document.getElementById(gameDivs["NewDivForGame_"+i].id).style.width ="35px";
       document.getElementById(gameDivs["NewDivForGame_"+i].id).style.height= "35px"; 
       document.getElementById(gameDivs["NewDivForGame_"+i].id).style.backgroundColor = "blue";
       console.log('Create size div run #'+i);
}

Of course, you don't even need to select them by their id if you have the reference to them, which you do:

for (i=0;i<=12;i++){
       // Before finally using square bracket notation to target the
       // properties by a dynamic name;
       gameDivs["NewDivForGame_"+i].style.width ="35px";
       gameDivs["NewDivForGame_"+i].style.height= "35px"; 
       gameDivs["NewDivForGame_"+i].style.backgroundColor = "blue";
       console.log('Create size div run #'+i);
}

This example assumes the divs are appended to the document.

This methodology uses square brackets on an object literal. As you may, or may not be aware, square brackets should be used when accessing an object's property in a dynamic way, such as what you were trying to do with string concatenation earlier.

Due to the way objects behave, you could even go so far as to generate the divs with a for-loop and then add them to the object:

let gameDivs = {};

for (let i = 0; i<=12; i++) {
    let gameDiv = document.createElement('div');
    gameDivs["NewDivForGame_"+i] = gameDiv;
    // append them too;
    document.body.appendChild(gameDiv);
}

Of course, I have no idea what pattern you're using for creating element ids, but in general the above would work.

Daedalus
  • 7,586
  • 5
  • 36
  • 61
  • Your explanation is better than mine. The solution is not an improvement. OP needs to post their HTML and then I am pretty sure we can refactor the whole thing with classes, CSS and a oneliner JS – mplungjan Nov 11 '22 at 09:54
  • @mplungjan The solution isn't really meant to be an improvement, but a way to teach the OP about things they did wrong. It is true they need to post their HTML, so we can teach them a better methodology of doing things. However, there's still a few unknowns beyond just HTML, such as targeted browsers, pre-existing constraints, and of course, the environment itself(school, etc). This does seem like an XY problem to me, but without further probing, this was the best I could do. – Daedalus Nov 11 '22 at 11:34