Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

269
Views
const elements defined in js module - cant access as DOM content not loaded yet

Using the below example. The const element test_el is null because the DOM content isn't loaded yet. So test() raises an error.

Wrapping the const definition in a onload event doesn't seem to work as its now now in the same scope as the function.

Whats the correct method of achieveing this - I know I can add the const within the function but it needs to be reused over multiple functions (not in this example)

main.js

import {test} from "../import.js" 
window.addEventListner("load", ()=>{
   test()
})

import.js

const test_el = document.getElementById("test_div")

export function test(){
    console.log(test_el.innerText)
}
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

// you can call
// all the tests that are dependent of `test_el` from one parent function
// after getting value of `test_el`

export function runTests() {
  const test_el = document.getElementById("test_div");
  if(test_el) {
   firstTest(test_el)
   secondTest(test_el)
 } else {
   throw new Error('Element not found.')
 }
}

function firstTest(element){
    assert(element.innerText.equal('someText'))
}

function secondTest(element){
    assert(element.classList.includes('someClass'))
}

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!