Home > Software design >  JS calling ID by variable
JS calling ID by variable

Time:11-11

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.

CodePudding user response:

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 us 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"))

CodePudding user response:

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';
  }
}

CodePudding user response:

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.

  • Related