Home > database >  HTMLCollection not working properly for created elements
HTMLCollection not working properly for created elements

Time:10-05

I populate a section of my HTML with cells.

Then I use getElementsByClassName to get a list of all my cerated cells.

My goal is to access elements of these cells through that list BUT when I try to get an element from HTMLCollection it returns undefined (the cells are all created without a problem and have all the features).

Strange is that console.log(cells) works well, I can see in the chrome console each of my created cells listed BUT as soon as I try to access it, it returns undefined and console.log(cells.length) returns 0.

let Uwidth = document.documentElement.clientWidth;
let Uhight = document.documentElement.clientHeight;
let maxGridLen = Math.floor(Uwidth * (15 / 700))
let maxGridHight = Math.floor(Uhight * (1 / 60))
let grid = document.getElementsByClassName("actualGrid")[0]
let cells = document.getElementsByClassName('cell')

window.addEventListener('load', populate)

function populate() {
  let column = 0
  let row = 0
  for (let i = 0; i < maxGridLen * maxGridHight; i  ) {
    createCell(column, row)
    column  
    if (column === maxGridLen) {
      row  
      column = 0
    }
  }
}

function createCell(column, row) {
  const cell = document.createElement("div")
  cell.classList.add("cell")
  cell.setAttribute("data-column", `${column}`)
  cell.setAttribute("data-row", `${row}`)
  cell.setAttribute("data-status", "dead")
  cell.setAttribute("onclick", "convertCell(this)")
  grid.appendChild(cell)
}

I have tried with no success waiting DOM loading, copying HTMLCollection (returns an empty array) and using querySelectorAll("cell")/querySelectorAll(".cell")

Please help I am desperate :'(

CodePudding user response:

You've probably linked javascript file with html in head tag, like so:

<html>
  <head>
     <script src="script.js">
  </head>
</html>

The problem with this access is that all your javaScript is loaded and executed before html is rendered, therefore that causes all html elements to be undefined (since they still don't exist). In order to avoid that problem you have few options:

  • Use existing way to link the script file, but the inside of script file should be like so:

      document.addEventListener('DOMContentLoaded', () => {
        // all of your functions and initialization of html elements goes in here
      });
    
  • Load script file asynchronously:

     <html>
       <head>
          <script src="script.js" async>
       </head>
     </html>
    
  • Defer loading script file:

     <html>
       <head>
          <script src="script.js" defer>
       </head>
     </html>
    
  • Link script file after all html elements:

     <html>
       <head>
    
       </head>
       <body>
       <!-- content -->
       <script src="script.js">
       </body>
     </html>
    

CodePudding user response:

Make sure your JavaScript is located after the elements you are trying to interact with, otherwise they will not be available by the time your script tries to execute. It's easiest if you keep your scripts at the bottom of any page you might create, otherwise you are asking for something that does not yet exist.

  • Related