1

How do you access a HTML element on the DOM from a class constructor in a JavaScript module?

I simply want to access this div

 <div class="loadingBar"></div>

Here is my module:

export default class LoadingBar
       {
        constructor(overlayGeometry, overlayMaterial,LoadingBarElement)
       {
       this.experience = new Experience()
       this.scene = this.experience.scene

    
       this.LoadingBarElement = document.querySelector('./index.html/loadingBar')
       console.log(LoadingBarElement)......

what am I doing wrong?

NadiaAli00098
  • 33
  • 1
  • 9
  • 1
    You're using a file/query path, but that's not how you access DOM elements. Whether you're doing this in a module or a non-module script doesn't make any difference. There's only one primary document. To find an element in it, just look in the document using a standard CSS selector as shown by the linked question's answers. For instance: `this.LoadingBarElement = document.querySelector(".loadingBar");` That will find and return the *first* element matching the `loadingBar` class that exists in the DOM as of the time you make that call. Since modules are always... – T.J. Crowder Mar 20 '22 at 18:44
  • 1
    ...[deferred](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script#attr-defer), then if that element is defined by the HTML of the page, it'll exist before your module code runs. (If you add it later, then of course you'll have to wait to go looking for it until later.) – T.J. Crowder Mar 20 '22 at 18:44
  • Thank you for such a fast reply! I'm definitely on the right track now but is there no need to reference the html file in the js or need to reference the js module in the html as I get an `undefined` error now? – NadiaAli00098 Mar 20 '22 at 19:21
  • 1
    There's no need to reference the HTML file in the JavaScript code. There is a need to reference the JavaScript code from the HTML file, so that it gets loaded and executed. For instance: ``. – T.J. Crowder Mar 21 '22 at 07:15

0 Answers0