Home > Enterprise >  How to wait for elements to be loaded in DOM in JavaScript?
How to wait for elements to be loaded in DOM in JavaScript?

Time:10-11

I have a problem with getting selector of an element in DOM, I placed the script source at the bottom of the HTML page and I also tried to wrap all codes in a function with "DOMContentLoaded" event, and it is still not working. in addition it disables jQuery that I am using it in my project.

This is how I get the selector:

const char = document.querySelectorAll('.text');
const num = document.querySelectorAll('span');

When I try to catch the selector in a function it works because it waits for the DOM to be loaded. I want to use these two variables in my code many times so I want them to be globally available and avoid repeating same line in many places.

Is there any way to wait for the DOM to be loaded and then get the elements selector globally?

CodePudding user response:

Define them globally and set the with DOMContentLoaded

let char;
let num;
window.addEventListener('DOMContentLoaded', function() {
    char = document.querySelectorAll('.text');
    num = document.querySelectorAll('span');
});

document.querySelector("button").addEventListener("click", () => {
  console.log(char);
  console.log(num);
});
<div class="text"><span></span></div>
<div class="text"><span></span></div>

<button>Test</button>

Or make a getter

const elems = {
  domChars: null,
  domNum: null,
  get chars() {
    if (this.domChars === null) {
      this.domChars = document.querySelectorAll('.text');
    }
    return this.domChars;
  },
  get nums() {
    if (this.domNum === null) {
      this.domNum = document.querySelectorAll('span');
    }
    return this.domNum;
  }
};


document.querySelector("button").addEventListener("click", () => {
  console.log(elems.chars);
  console.log(elems.nums);
});
<div class="text"><span></span></div>
<div class="text"><span></span></div>

<button>Test</button>

  • Related