0
const parentDiv = document.querySelector(".parent-div");

for (var i = 0; i < 10; i++) {

    var childDiv = document.createElement("div");
    childDiv.style.display = "flex";
    childDiv.style.flex = "1";

    for (var k = 0; k < 10; k++) {
        var newChild = document.createElement("div");
        newChild.style.flex = "1";
        newChild.style.height = "48px";
        newChild.style.width = "48px";
        newChild.style.border = "2px black solid";
        newChild.style.color = "#f389ca";

        newChild.addEventListener("mouseover", function(){
            newChild.style.color = "#8e2db8";
        });

        newChild.addEventListener("mouseout", function(){
            newChild.style.color = "#f389ca";
        });

        childDiv.appendChild(newChild);
    }

    parentDiv.appendChild(childDiv);
}

i want to dynamically create a row of square divs, then multiple such rows and add them to the parent-div already in the HTML file.

edit: script was loading before the parent-div element, hence it wasn't creating any squares in it

solution: either load the js file at the end of body or use

edit2: use CSS: background-color instead of color

  • Can you also show the HTML? At a glance I don't see anything wrong. – Oskar Grosser Jun 09 '23 at 21:36
  • 1
    Are you getting any errors? For example, is your HTML fully loaded before you run the JS? – A Haworth Jun 09 '23 at 21:47
  • Does this answer your question? [Why does jQuery or a DOM method such as getElementById not find the element?](https://stackoverflow.com/questions/14028959/why-does-jquery-or-a-dom-method-such-as-getelementbyid-not-find-the-element) – Oskar Grosser Jun 09 '23 at 23:17

1 Answers1

0

You should use

newChild.style.backgroundColor = blabla;

instead of

newChild.style.color = blabla;

.color is for text color.

Edit: I runed your code and please do not use var for variables unless you know about hoisting and scopes :))

TLDR So replace "var" with "let" for all variables

Cuz addEventListener works but instead of creating a new variable for each newChild, it overwrites it, and all addEventListeners use just the last newChild created.

  ...
  const parentDiv = document.querySelector(".parent-div");
  // will be hoisted here: 
  // var newChild
  // var childDiv
  for (var i = 0; i < 10; i++) {
  ...
  • The code works fine, even when using `var`. The hoisting of the variable doesn't change the fact that it is assigned a new element in each iteration; all listeners are added to the correct (i.e. the current iteration's) element. – Oskar Grosser Jun 09 '23 at 23:20